Mybatis开发要点-resultType和resultMap有什么区别详解

2023-01-21 0 1,401

目录

Mybatis返回Xml返回值有resultType和resultMap,我们一般都该如何选择呢?

一、resultType

1、resultType介绍

当使用resultType做SQL语句返回结果类型处理时,对于SQL语句查询出的字段在相应的pojo中必须有和它相同的字段对应,而resultType中的内容就是pojo在本项目中的位置。

2、映射规则

  • 基本类型  :resultType=基本类型  
  • List类型:   resultType=List中元素的类型
  • Map类型    单条记录:resultType =map    多条记录:resultType =Map中value的类型

3、自动映射注意事项

  • 前提:SQL列名和JavaBean的属性是一致的;
  • 使用resultType,如用简写需要配置typeAliases (别名);
  • 如果列名和JavaBean不一致,但列名符合单词下划线分割,Java是驼峰命名法,则mapUnderscoreToCamelCase可设置为true;

4、代码演示

1、t_user_test.sql准备

CREATE TABLE `t_user_test` (
  `id` int(20) NOT NULL AUTO_INCREMENT,
  `user_name` varchar(60) DEFAULT NULL COMMENT \'用户名称\',
  `real_name` varchar(60) DEFAULT NULL COMMENT \'真实名称\',
  `sex` tinyint(3) DEFAULT NULL COMMENT \'姓名\',
  `mobile` varchar(20) DEFAULT NULL COMMENT \'电话\',
  `email` varchar(60) DEFAULT NULL COMMENT \'邮箱\',
  `note` varchar(200) DEFAULT NULL COMMENT \'备注\',
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=142 DEFAULT CHARSET=utf8;码

2、实体类

package com.enjoylearning.mybatis.entity;

import java.io.Serializable;
import java.util.List;

import org.apache.ibatis.annotations.Param;

import com.mysql.jdbc.Blob;

public class TUser implements Serializable{
	
    private Integer id;

    private String userName;

    private String realName;

    private Byte sex;

    private String mobile;

    private String email;

    private String note;

    private TPosition position;
    
    private List<TJobHistory> jobs ;
    
    private List<HealthReport> healthReports;

    
    private List<TRole> roles;


  
	@Override
	public String toString() {
		String positionId=  (position == null ? \"\" : String.valueOf(position.getId()));
		return \"TUser [id=\" + id + \", userName=\" + userName + \", realName=\"
				+ realName + \", sex=\" + sex + \", mobile=\" + mobile + \", email=\"
				+ email + \", note=\" + note + \", positionId=\" + positionId + \"]\";
	}


	public Integer getId() {
		return id;
	}
	public void setId(Integer id) {
		this.id = id;
	}
	public String getUserName() {
		return userName;
	}
	public void setUserName(String userName) {
		this.userName = userName;
	}
	public String getRealName() {
		return realName;
	}
	public void setRealName(String realName) {
		this.realName = realName;
	}
	
	public Byte getSex() {
		return sex;
	}

	public void setSex(Byte sex) {
		this.sex = sex;
	}


	public String getMobile() {
		return mobile;
	}


	public void setMobile(String mobile) {
		this.mobile = mobile;
	}


	public String getEmail() {
		return email;
	}


	public void setEmail(String email) {
		this.email = email;
	}


	public String getNote() {
		return note;
	}

	public void setNote(String note) {
		this.note = note;
	}


	public TPosition getPosition() {
		return position;
	}


	public void setPosition(TPosition position) {
		this.position = position;
	}

	public List<TJobHistory> getJobs() {
		return jobs;
	}


	public void setJobs(List<TJobHistory> jobs) {
		this.jobs = jobs;
	}

	public List<HealthReport> getHealthReports() {
		return healthReports;
	}

	public void setHealthReports(List<HealthReport> healthReports) {
		this.healthReports = healthReports;
	}

	public List<TRole> getRoles() {
		return roles;
	}

	public void setRoles(List<TRole> roles) {
		this.roles = roles;
	}

}

3、Mapper接口

public interface TUserTestMapper {
	
	TUser selectByPrimaryKey(Integer id);
	List<TUser> selectAll();

}

4、Mapper xml

<?xml version=\"1.0\" encoding=\"UTF-8\" ?>
<!DOCTYPE mapper PUBLIC \"-//mybatis.org//DTD Mapper 3.0//EN\" \"http://mybatis.org/dtd/mybatis-3-mapper.dtd\" >
<mapper namespace=\"com.mybatis.mapper.TUserTestMapper\">


	<select id=\"selectByPrimaryKey\" resultType=\"TUser\">
		select
		id, user_name, real_name, sex, mobile, email, note
		from t_user_test
		where id = #{id,jdbcType=INTEGER}
	</select>
	
	
	<select id=\"selectAll\" resultType=\"TUser\">
		select
		id, user_name, real_name, sex, mobile, email, note
		from t_user_test
	</select>


</mapper>

5、配置文件

<?xml version=\"1.0\" encoding=\"UTF-8\" ?>
<!DOCTYPE configuration PUBLIC \"-//mybatis.org//DTD Config 3.0//EN\" \"http://mybatis.org/dtd/mybatis-3-config.dtd\">
<configuration>

	<properties resource=\"db.properties\"/>
	
 	<settings>
		<!-- 设置自动驼峰转换		 -->
		<setting name=\"mapUnderscoreToCamelCase\" value=\"true\" />

		<!-- 开启懒加载 -->		
		 <!-- 当启用时,有延迟加载属性的对象在被调用时将会完全加载任意属性。否则,每种属性将会按需要加载。默认:true -->
	  <setting name=\"aggressiveLazyLoading\" value=\"false\" />

	</settings>
	<!-- 别名定义 -->
	<typeAliases>
		<package name=\"com.enjoylearning.mybatis.entity\" />
	</typeAliases>
	
 	<plugins>
		<plugin interceptor=\"com.enjoylearning.mybatis.Interceptors.ThresholdInterceptor\"> 
			<property name=\"threshold\" value=\"10\"/>
		</plugin>
			
  		 <plugin interceptor=\"com.github.pagehelper.PageInterceptor\">
			<property name=\"pageSizeZero\" value=\"true\" />
		</plugin>
	</plugins>


	<!--配置environment环境 -->
	<environments default=\"development\">
		<!-- 环境配置1,每个SqlSessionFactory对应一个环境 -->
		<environment id=\"development\">
			<transactionManager type=\"JDBC\" />
			<dataSource type=\"POOLED\">
				<property name=\"driver\" value=\"com.mysql.jdbc.Driver\" />
				<property name=\"url\" value=\"jdbc:mysql://ip:port/test?useUnicode=true\" />
				<property name=\"username\" value=\"root\" />
				<property name=\"password\" value=\"123456\" />
			</dataSource>
		</environment>
	</environments>

	<!-- 映射文件,mapper的配置文件 -->
	<mappers>
		<!--直接映射到相应的mapper文件 -->
		<mapper resource=\"sqlmapper/TUserTestMapper.xml\" />
	</mappers>

</configuration>  

6、启动测试

public class MybatisDemo2 {
	
	private SqlSessionFactory sqlSessionFactory;
	
	@Before
	public void init() throws IOException {
		//--------------------第一阶段---------------------------
	    // 1.读取mybatis配置文件创SqlSessionFactory
		String resource = \"mybatis-config.xml\";
		InputStream inputStream = Resources.getResourceAsStream(resource);
		// 1.读取mybatis配置文件创SqlSessionFactory
		sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
		inputStream.close();
	}

	@Test
	//知识点:resultType
	public void testAutoMapping() throws IOException {
		// 2.获取sqlSession	
		SqlSession sqlSession = sqlSessionFactory.openSession();
		// 3.获取对应mapper
		TUserTestMapper mapper = sqlSession.getMapper(TUserTestMapper.class);
		// 4.执行查询语句并返回多条数据
		
		List<TUser> users = mapper.selectAll();
		for (TUser tUser : users) {
			System.out.println(tUser);
		}
		
	}
	
}

7、执行结果

sql语句:“com.mysql.jdbc.JDBC4PreparedStatement@654f0d9c: select
		id, user_name, real_name, sex, mobile, email, note
		from t_user_test”执行时间为:35毫秒,已经超过阈值!
TUser [id=1, userName=zhangsan, realName=张三, sex=1, mobile=186995587411, email=zhangsan@qq.com, note=zhangsan的备注, positionId=]
TUser [id=2, userName=lisi, realName=李四, sex=1, mobile=18677885200, email=lisi@qq.com, note=lisi的备注, positionId=]
TUser [id=3, userName=wangwu, realName=王五, sex=2, mobile=18695988747, email=xxoo@163.com, note=wangwu\'s note, positionId=]

resultType当返基本类型的时候建议选择,当返回POJO类的时候由于需要完全和数据库字段进行对应,存在不灵活、问题排查难等问题。

二、resultMap

1、resultMap  介绍

resultMap 元素是 MyBatis 中最重要最强大的元素。它可以让你从 90% 的 JDBC ResultSets 数据提取代码中解放出来,在对复杂语句进行联合映射的时候,它很可能可以代替数千行的同等功能的代码。ResultMap 的设计思想是,简单的语句不需要明确的结果映射,而复杂一点的语句只需要描述它们的关系就行了。

2、resultMap属性

   
属性 描述
id 当前命名空间中的一个唯一标识,用于标识一个result map.
type 类的完全限定名, 或者一个类型别名.
autoMapping 如果设置这个属性,MyBatis将会为这个ResultMap开启或者关闭自动映射。这个属性会覆盖全局的属性 autoMappingBehavior。默认值为:unset。

3、使用场景

  • 字段有自定义的转化规则
  • 复杂的多表查询

4、resultMap子元素属性

  • id –一个 ID 结果;标记出作为 ID 的结果可以帮助提高整体性能,一对多的查询中用于结果集合并;
  • result – 注入到字段或 JavaBean 属性的普通结果
  • association – 一个复杂类型的关联;许多结果将包装成这种类型。关联可以指定为一个 resultMap 元素,或者引用一个
  • collection – 一个复杂类型的集合

5、代码演示

实体类,配置文件同上

1、mapper接口

public interface TUserMapper {
	List<TUser> selectTestResultMap();
}

2、Mapper.xml

<?xml version=\"1.0\" encoding=\"UTF-8\" ?>
<!DOCTYPE mapper PUBLIC \"-//mybatis.org//DTD Mapper 3.0//EN\" \"http://mybatis.org/dtd/mybatis-3-mapper.dtd\" >
<mapper namespace=\"com.mybatis.mapper.TUserMapper\">

	<resultMap id=\"UserResultMap\" type=\"TUser\" autoMapping=\"true\">
		<id column=\"id\" property=\"id\" />
        <result column=\"userName\" property=\"userName\"/>
		<result column=\"realName\" property=\"realName\" />
		<result column=\"sex\" property=\"sex\" />
		<result column=\"mobile\" property=\"mobile\" />
		<result column=\"email\" property=\"email\" />
		<result column=\"note\" property=\"note\" />
		<association property=\"position\" javaType=\"TPosition\" columnPrefix=\"post_\">
			<id column=\"id\" property=\"id\"/>
			<result column=\"name\" property=\"postName\"/>
			<result column=\"note\" property=\"note\"/>
		</association>
	</resultMap>

	<select  id=\"selectTestResultMap\" resultMap=\"UserResultMap\" >
		select
		    a.id,
		    userName,
			realName,
			sex,
			mobile,
			email,
			a.note,
			b.id  post_id,
			b.post_name,
			b.note post_note
		from t_user a,
			t_position b
		where a.position_id = b.id

	</select>

</mapper>

3、启动测试

public class MybatisDemo2 {
	

	private SqlSessionFactory sqlSessionFactory;
	
	@Before
	public void init() throws IOException {
		//--------------------第一阶段---------------------------
	    // 1.读取mybatis配置文件创SqlSessionFactory
		String resource = \"mybatis-config.xml\";
		InputStream inputStream = Resources.getResourceAsStream(resource);
		// 1.读取mybatis配置文件创SqlSessionFactory
		sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
		inputStream.close();
	}


	
	@Test
	public void testResultMap() throws IOException {
		//--------------------第二阶段---------------------------
		// 2.获取sqlSession	
		SqlSession sqlSession = sqlSessionFactory.openSession();
		// 3.获取对应mapper
		TUserMapper mapper = sqlSession.getMapper(TUserMapper.class);
		
		//--------------------第三阶段---------------------------

		// 4.执行查询语句并返回单条数据
		List<TUser> users = mapper.selectTestResultMap();
		for (TUser tUser : users) {
			System.out.println(tUser.getUserName());
			System.out.println(tUser.getPosition().getPostName());
		}
	}
}

4、执行结果

sql语句:“com.mysql.jdbc.JDBC4PreparedStatement@19bb07ed: select
            a.id,
            userName,
            realName,
            sex,
            mobile,
            email,
            a.note,
            b.id  post_id,
            b.post_name,
            b.note post_note
        from t_user a,
            t_position b
        where a.position_id = b.id”执行时间为:52毫秒,已经超过阈值!
zhangsan
总经理
lisi
零时工
wangwu
总经理

三、结论

当返回对象为基础类型时建议走resultType,当返回对象为POJO时,强制走resultMap。同时可以参考阿里巴巴JAVA开发手册中的5.4.3节,返回要解耦,不讷讷更直接使用resultClass。

:本文采用 知识共享署名-非商业性使用-相同方式共享 4.0 国际许可协议 进行许可, 转载请附上原文出处链接。
1、本站提供的源码不保证资源的完整性以及安全性,不附带任何技术服务!
2、本站提供的模板、软件工具等其他资源,均不包含技术服务,请大家谅解!
3、本站提供的资源仅供下载者参考学习,请勿用于任何商业用途,请24小时内删除!
4、如需商用,请购买正版,由于未及时购买正版发生的侵权行为,与本站无关。
5、本站部分资源存放于百度网盘或其他网盘中,请提前注册好百度网盘账号,下载安装百度网盘客户端或其他网盘客户端进行下载;
6、本站部分资源文件是经压缩后的,请下载后安装解压软件,推荐使用WinRAR和7-Zip解压软件。
7、如果本站提供的资源侵犯到了您的权益,请邮件联系: 442469558@qq.com 进行处理!

猪小侠源码-最新源码下载平台 Java教程 Mybatis开发要点-resultType和resultMap有什么区别详解 https://www.20zxx.cn/463043/xuexijiaocheng/javajc.html

猪小侠源码,优质资源分享网

常见问题
  • 本站所有资源版权均属于原作者所有,均只能用于参考学习,请勿直接商用。若由于商用引起版权纠纷,一切责任均由使用者承担
查看详情
  • 最常见的情况是下载不完整: 可对比下载完压缩包的与网盘上的容量,建议提前注册好百度网盘账号,使用百度网盘客户端下载
查看详情

相关文章

官方客服团队

为您解决烦忧 - 24小时在线 专业服务