Mybatis development points - what is the difference between resultType and resultMap?

Get into the habit of writing together! This is the third day of my participation in the "Nuggets Daily New Plan · April Update Challenge", click to view the details of the event


Mybatis returns Xml. The return values ​​are resultType and resultMap. How do we generally choose?

1. resultType

1. Introduction to resultType

When using resultType to process the result type returned by an SQL statement, the field queried by the SQL statement must have the same field corresponding to it in the corresponding pojo, and the content of resultType is the position of the pojo in this project.

2. Mapping rules

  1. Basic type: resultType=basic type  
  2. List type: resultType=type of elements in the List
  3. Map type Single record: resultType = map Multiple records: resultType = type of value in Map

3. Notes on automatic mapping

  1. Premise: SQL column names and JavaBean properties are consistent;
  2. Use resultType, if you use shorthand, you need to configure typeAliases (alias);
  3. If the column name is inconsistent with JavaBean, but the column name conforms to the word underscore separation, and Java is the camel case nomenclature, then mapUnderscoreToCamelCase can be set to true;

4. Code demo

1. Preparation of 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. Entity class

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 interface class

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. Configuration file

<?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. Start the test class

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. Execution results

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 protected], note=zhangsan的备注, positionId=]
TUser [id=2, userName=lisi, realName=李四, sex=1, mobile=18677885200, [email protected], note=lisi的备注, positionId=]
TUser [id=3, userName=wangwu, realName=王五, sex=2, mobile=18695988747, [email protected], note=wangwu's note, positionId=]
复制代码

It is recommended to select resultType when returning the basic type. When returning the POJO class, it needs to completely correspond to the database field, which is inflexible and difficult to troubleshoot.

2. resultMap

1. Introduction to resultMap

The resultMap element is the most important and powerful element in MyBatis. It frees you from 90% of the JDBC ResultSets data extraction code, and it is likely to replace thousands of lines of equivalent code when it comes to joint mapping of complex statements. The design idea of ​​ResultMap is that simple statements do not need explicit result mapping, while more complex statements only need to describe their relationships.

2. The resultMap property

Attributes describe
id A unique identifier in the current namespace that identifies a result map.
type The fully qualified name of the class, or a type alias.
autoMapping If this property is set, MyBatis will enable or disable automatic mapping for this ResultMap. This property overrides the global property autoMappingBehavior. Default is: unset.

3. Usage scenarios

  1. Fields have custom conversion rules
  2. complex multi-table query

4, resultMap child element attributes

  1. id – an ID result; marking the result as an ID can help improve overall performance, used for result set merging in one-to-many queries;
  2. result – the normal result injected into the field or JavaBean property
  3. association – an association of a complex type; many results will be wrapped into this type. Associations can be specified as a resultMap element, or reference a
  4. collection – a collection of complex types

5. Code demo

Entity class, the configuration file is the same as above

1. mapper interface



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. Start the test


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. Execution results

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
总经理
复制代码

3. Conclusion

When the returned object is a basic type, it is recommended to use resultType, and when the returned object is POJO, it is forced to use resultMap. At the same time, you can refer to Section 5.4.3 in the Alibaba JAVA Development Manual. The return should be decoupled, and the resultClass should be used directly.

Guess you like

Origin juejin.im/post/7082352714297901064