Mybatis returns Xml with resultType and resultMap.
When you meet new people, you need to meet new people’s congresses. When you meet new people, you need to meet new people’s congresses. When you meet new people’s congresses, you need to meet new people’s congresses. JAVA Basics – Intermediate – Advanced Interviews +SSM framework + Distributed + Performance tuning + Microservices + concurrent programming + Networking + Design patterns + data structures and algorithms
A, resultType
1.1 introduce resultType
When processing the resultType returned by SQL statements using resultType, the fields queried by SQL statements must have the same field in the corresponding pojo, and the content in the resultType is the position of the pojo in the project.
1.2 Mapping Rules
-
Basic type: resultType= Basic type
-
List type: resultType= The type of the element in the List
-
Map Type One record: resultType =Map Multiple records: resultType = Value type in the Map
1.3 Precautions for Automatic Mapping
-
Prerequisite: SQL column names are consistent with JavaBean attributes;
-
If resultType is used, typeAliases (alias) needs to be configured.
-
MapUnderscoreToCamelCase can be set to true if the column name is inconsistent with the JavaBean, but the column name conforms to the word underline, and Java is a camel name.
1.4 Code Demonstration
T_user_test.sql is ready
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 'iD ',' sex 'tinyint(3) DEFAULT NULL COMMENT' iD ', 'mobile' varchar(20) DEFAULT NULL COMMENT 'phone ',' email 'varchar(60) DEFAULT NULL COMMENT' email ', 'note' varchar(200) DEFAULT NULL COMMENT '注 意 ', PRIMARY KEY (`id`) ) ENGINE=InnoDB AUTO_INCREMENT=142 DEFAULT CHARSET=utf8;Copy the code
(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; }}Copy the code
(3) Mapper interface class
public interface TUserTestMapper {
TUser selectByPrimaryKey(Integer id);
List<TUser> selectAll();
}
Copy the code
(4) Mapper XML
<? The 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>Copy the code
(5) Configuration file
<? The 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" /> <! -- Enable lazy loading --> <! When enabled, objects with lazy loading properties will be fully loaded with any properties when called. Otherwise, each attribute will be loaded as needed. Default: true -> <setting name=" introduction to sivelazyloading "value="false" /> </ Settings > <! - alias definition - > < 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 default="development"> <! -- Environment configuration 1, Each SqlSessionFactory corresponds to an environment --> <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> <! -- map file, mapper configuration file --> <mappers> <! - directly mapped to the corresponding mapper file - > < mapper resource = "sqlmapper/TUserTestMapper. XML" / > < / mappers > < / configuration >Copy the code
(6) Start the test class
public class MybatisDemo2 { private SqlSessionFactory sqlSessionFactory; @ Before public void init () throws IOException {/ / -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- the first stage -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- / / 1. SqlSessionFactory String resource = "mybatis-config.xml"; InputStream inputStream = Resources.getResourceAsStream(resource); SqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream); inputStream.close(); ResultType public void testAutoMapping() throws IOException {// 2. Get sqlSession sqlSession sqlSession = sqlSessionFactory. OpenSession (); GetMapper (TUserTestMapper) = sqlsession. getMapper(tUserTestmapper.class); List<TUser> users = mapper.selectAll(); // 4. for (TUser tUser : users) { System.out.println(tUser); }}}Copy the code
(7) Execution results
The SQL statement: "com. Mysql. JDBC. JDBC4PreparedStatement @ 654 f0d9c: Select id, user_name, real_name, sex, mobile, email, note from T_user_test. TUser [id=1, userName=zhangsan, realName= zhangsan, sex=1, mobile=186995587411, [email protected], note=zhangsan PositionId =] TUser [id=2, userName=lisi, realName= Lisi, sex=1, mobile=18677885200, [email protected], note=lisi PositionId =] TUser [ID =3, userName= Wangwu, realName= Wangwu, sex=2, mobile=18695988747, [email protected], note=wangwu's note, positionId=]Copy the code
ResultType You are advised to select this parameter when returning the basic type. When returning the POJO class, it needs to completely correspond to the database field, resulting in inflexible problems and difficulty in troubleshooting.
Second, the resultMap
2.1 introduce resultMap
The resultMap element is the most important and powerful element in MyBatis. It frees you up to 90% of the JDBC ResultSets data extraction code, and it can potentially replace thousands of lines of code with equivalent functionality for joint mapping of complex statements. The idea behind ResultMap is that simple statements do not need explicit result mappings, while more complex statements only need to describe their relationships.
2.2 resultMap properties
2.3 Application Scenarios
-
Fields have custom conversion rules
-
Complex multi-table queries
2.4 resultMap Subelement attributes
-
Id – an ID result; Marking results as ids can help improve overall performance, and is used for result set unions in one-to-many queries;
-
Result – A normal result injected into a field or JavaBean property
-
Association – an association of a complex type; Many results will be wrapped in this type. Associations can be specified as a resultMap element, or reference one
-
Collection – A collection of complex types
2.5 Code Demo
Entity class, configuration file same as above
(1) Mapper interface
public interface TUserMapper {
List<TUser> selectTestResultMap();
}
Copy the code
(2) Mapper XML
<? The 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>Copy the code
(3) Start the test
public class MybatisDemo2 { private SqlSessionFactory sqlSessionFactory; @ Before public void init () throws IOException {/ / -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- the first stage -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- / / 1. SqlSessionFactory String resource = "mybatis-config.xml"; InputStream inputStream = Resources.getResourceAsStream(resource); SqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream); inputStream.close(); } @ Test public void testResultMap () throws IOException {/ / -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- the second stage -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- / / 2. Get sqlSession sqlSession sqlSession = sqlSessionFactory. OpenSession (); GetMapper (TUserMapper) = sqlsession.getmapper (tUsermapper.class); / / -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- the third stage -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- - / / 4. Execute the query and returns a single data List < TUser > users = mapper. SelectTestResultMap (); for (TUser tUser : users) { System.out.println(tUser.getUserName()); System.out.println(tUser.getPosition().getPostName()); }}}Copy the code
(4) Execution results
SQL statements: "com. Mysql. JDBC. 19 bb07ed JDBC4PreparedStatement @ : 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. osition_id = B. id "The execution time is 52 milliseconds, which exceeds the threshold. Zhangsan general manager lisi part-time worker wangwu general managerCopy the code
Third, the conclusion
If the returned object is a basic type, resultType is recommended; if the returned object is POJO, resultMap is mandatory. At the same time, we can refer to Section 5.4.3 of Alibaba JAVA Development manual to decouple the return and use resultClass more directly without stumbling.