Mybatis开发要点:resultType和resultMap的区别?

·  阅读 842
Mybatis开发要点:resultType和resultMap的区别?

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

阅读彩蛋:小编也整理了很全面的 Java一线大厂高岗面试题解析合集,现在免费分享给阅读到本篇文章的Java程序员朋友们,需要的自行领取
☛Java一线大厂高岗面试题解析合集:JAVA基础-中级-高级面试+SSM框架+分布式+性能调优+微服务+并发编程+网络+设计模式+数据结构与算法

一、resultType

1.1 resultType介绍

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

1.2 映射规则

  • 基本类型 :resultType=基本类型

  • List类型: resultType=List中元素的类型

  • Map类型 单条记录:resultType =map 多条记录:resultType =Map中value的类型

1.3 自动映射注意事项

  • 前提:SQL列名和JavaBean的属性是一致的;

  • 使用resultType,如用简写需要配置typeAliases (别名);

  • 如果列名和JavaBean不一致,但列名符合单词下划线分割,Java是驼峰命名法,则mapUnderscoreToCamelCase可设置为true;

1.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

2.1 resultMap 介绍

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

2.2 resultMap属性

2.3 使用场景

  • 字段有自定义的转化规则

  • 复杂的多表查询

2.4 resultMap子元素属性

  • id –一个 ID 结果;标记出作为 ID 的结果可以帮助提高整体性能,一对多的查询中用于结果集合并;

  • result – 注入到字段或 JavaBean 属性的普通结果

  • association – 一个复杂类型的关联;许多结果将包装成这种类型。关联可以指定为一个 resultMap 元素,或者引用一个

  • collection – 一个复杂类型的集合

2.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。

分类:
后端
标签: