Home Java javaTutorial Detailed introduction to resultmap of mybatis tutorial

Detailed introduction to resultmap of mybatis tutorial

Sep 02, 2017 am 10:34 AM
mybatis introduce

This article mainly introduces the resultmap of the mybatis tutorial. The editor thinks it is quite good. Now I will share it with you and give it as a reference. Let’s follow the editor and take a look.

SQL mapping XML file is where all sql statements are placed. A workspace needs to be defined, which is generally defined as the path to the corresponding interface class. After writing the SQL statement mapping file, it needs to be quoted in the mappers tag of the MyBAtis configuration file, for example:


##

<mappers> 
  <mapper resource="com/bjpowernode/manager/data/mappers/UserMapper.xml" /> 
  <mapper resource="com/bjpowernode/manager/data/mappers/StudentMapper.xml" /> 
  <mapper resource="com/bjpowernode/manager/data/mappers/ClassMapper.xml" /> 
  <mapper resource="com/bjpowernode/manager/data/mappers/TeacherMapper.xml" /> 
</mappers>
Copy after login

When the Java interface and XML file are in a relative path When, it does not need to be declared in the mappers of the myBatis configuration file.

Some basic elements of SQL mapping XML files:

1. cache – configure the cache for a given schema

2. cache-ref – reference a cache from another schema
3. resultMap – This is the most complex but powerful element, which describes how to load objects from the result set
4. sql – a SQL block that can be reused by other statements
5. insert – mapping INSERT statement
6. update – maps UPDATE statement
7. delete – maps DELEETE statement
8. select – maps SELECT statement

2.1 resultMap

resultMap is the most important and powerful element in MyBatis. You can save 90% of the code than using JDBC to call the result set, and it also allows you to do many things that JDBC does not support. In fact, it may take thousands of lines of code to write a complex statement equivalent to an interactive mapping. The purpose of ResultMaps is to use such simple statements without the need for redundant result mapping. For more complex statements, no more is needed except for some absolutely necessary statements to describe relationships.


resultMap attribute: type is the java entity class; id is the identifier of the resultMap.


resultMap can set the mapping:

1. constructor – a constructor used to reflect the result to an instantiated class


a ) idArg – ID parameter; mark the result set as ID to facilitate global calls

b) arg – the usual result reflected to the constructor

2. id – ID result, mark the result set as ID , to facilitate global calls

3. result – the ordinary result reflected to the JavaBean property

4. association – the combination of complex types; the type of multiple result synthesis


a) nested result mappings – several resultMap nested relationships within itself, or can be referenced to another one

5. collection – a collection of complex types

6. nested result mappings – a collection of resultMap, which can also be referenced to another one

7. discriminator – uses a result value to decide which resultMap to use


a) case – the result of some basic value Mapped case situations


i. Nested result mappings – A case situation is itself a result map, so it can also contain some of the same elements, or it can reference an external resultMap.


id, result

id, result is the simplest mapping, id is the primary key mapping; result is other basic database table fields to entity classes Mapping of properties.


The simplest example:



<resultMap type="bjpowernodestudentmanagerdatamodelStudentEntity" id="studentResultMap"> 
  <id property="studentId"    column="STUDENT_ID" javaType="String" jdbcType="VARCHAR"/> 
  <result property="studentName"    column="STUDENT_NAME" javaType="String" jdbcType="VARCHAR"/> 
  <result property="studentSex"    column="STUDENT_SEX" javaType="int" jdbcType="INTEGER"/> 
  <result property="studentBirthday"  column="STUDENT_BIRTHDAY" javaType="Date" jdbcType="DATE"/> 
  <result property="studentPhoto" column="STUDENT_PHOTO" javaType="byte[]" jdbcType="BLOB" typeHandler="orgapacheibatistypeBlobTypeHandler" /> 
</resultMap>
Copy after login

id, result statement attribute configuration details:


Property Description


##propertyThe property name that needs to be mapped to JavaBean. columnThe column name or label of the data table Alias. javaTypeA complete class name, or is a type alias. If you match a JavaBean, MyBatis will usually detect it on its own. Then, if you want to map to a HashMap, then you need to specify the purpose of javaType. jdbcTypeList of types supported by the data table. This attribute is only useful for columns that allow nulls during insert, update or delete. JDBC requires this, but MyBatis does not. If you are coding directly against JDBC and have columns that allow nulls, you will want to specify this. typeHandlerUse this attribute to override the type processor. This value can be a complete class name or a type alias.

支持的JDBC类型

为了将来的引用,MyBatis 支持下列JDBC 类型,通过JdbcType 枚举:

BIT,FLOAT,CHAR,TIMESTAMP,OTHER,UNDEFINED,TINYINT,REAL,VARCHAR,BINARY,BLOB,NVARCHAR,SMALLINT,DOUBLE,LONGVARCHAR,VARBINARY,CLOB,NCHAR,INTEGER,NUMERIC,DATE,LONGVARBINARY,BOOLEAN,NCLOB,BIGINT,DECIMAL,TIME,NULL,CURSOR

constructor

我们使用id、result时候,需要定义java实体类的属性映射到数据库表的字段上。这个时候是使用JavaBean实现的。当然我们也可以使用实体类的构造方法来实现值的映射,这个时候是通过构造方法参数的书写的顺序来进行赋值的。

使用construcotr功能有限(例如使用collection级联查询)。

上面使用id、result实现的功能就可以改为:


<resultMap type="StudentEntity" id="studentResultMap" > 
  <constructor> 
    <idArg javaType="String" column="STUDENT_ID"/> 
    <arg javaType="String" column="STUDENT_NAME"/> 
    <arg javaType="String" column="STUDENT_SEX"/> 
    <arg javaType="Date" column="STUDENT_BIRTHDAY"/> 
  </constructor> 
</resultMap>
Copy after login

当然,我们需要定义StudentEntity实体类的构造方法:


public StudentEntity(String studentID, String studentName, String studentSex, Date studentBirthday){ 
  this.studentID = studentID; 
  this.studentName = studentName; 
  this.studentSex = studentSex; 
  this.studentBirthday = studentBirthday; 
}
Copy after login

association联合

联合元素用来处理“一对一”的关系。需要指定映射的Java实体类的属性,属性的javaType(通常MyBatis 自己会识别)。对应的数据库表的列名称。如果想覆写的话返回结果的值,需要指定typeHandler。

不同情况需要告诉MyBatis 如何加载一个联合。MyBatis 可以用两种方式加载:

1. select: 执行一个其它映射的SQL 语句返回一个Java实体类型。较灵活;

2. resultsMap: 使用一个嵌套的结果映射来处理通过join查询结果集,映射成Java实体类型。

例如,一个班级对应一个班主任。

首先定义好班级中的班主任属性:


private TeacherEntity teacherEntity;
Copy after login

使用select实现联合

例:班级实体类中有班主任的属性,通过联合在得到一个班级实体时,同时映射出班主任实体。
这样可以直接复用在TeacherMapper.xml文件中定义好的查询teacher根据其ID的select语句。而且不需要修改写好的SQL语句,只需要直接修改resultMap即可。

ClassMapper.xml文件部分内容:


<resultMap type="ClassEntity" id="classResultMap"> 
  <id property="classID" column="CLASS_ID" /> 
  <result property="className" column="CLASS_NAME" /> 
  <result property="classYear" column="CLASS_YEAR" /> 
  <association property="teacherEntity" column="TEACHER_ID" select="getTeacher"/> 
</resultMap> 
 
<select id="getClassByID" parameterType="String" resultMap="classResultMap"> 
  SELECT * FROM CLASS_TBL CT 
  WHERE CTCLASS_ID = #{classID}; 
</select>
Copy after login

TeacherMapper.xml文件部分内容:


<resultMap type="TeacherEntity" id="teacherResultMap"> 
  <id property="teacherID" column="TEACHER_ID" /> 
  <result property="teacherName" column="TEACHER_NAME" /> 
  <result property="teacherSex" column="TEACHER_SEX" /> 
  <result property="teacherBirthday" column="TEACHER_BIRTHDAY"/> 
  <result property="workDate" column="WORK_DATE"/> 
  <result property="professional" column="PROFESSIONAL"/> 
</resultMap> 
 
<select id="getTeacher" parameterType="String" resultMap="teacherResultMap"> 
  SELECT * 
   FROM TEACHER_TBL TT 
   WHERE TT.TEACHER_ID = #{teacherID} 
</select>
Copy after login

使用resultMap实现联合

与上面同样的功能,查询班级,同时查询器班主任。需在association中添加resultMap(在teacher的xml文件中定义好的),新写sql(查询班级表left join教师表),不需要teacher的select。

修改ClassMapper.xml文件部分内容:


<resultMap type="ClassEntity" id="classResultMap"> 
  <id property="classID" column="CLASS_ID" /> 
  <result property="className" column="CLASS_NAME" /> 
  <result property="classYear" column="CLASS_YEAR" /> 
  <association property="teacherEntity" column="TEACHER_ID" resultMap="teacherResultMap"/> 
</resultMap> 
 
<select id="getClassAndTeacher" parameterType="String" resultMap="classResultMap"> 
  SELECT * 
   FROM CLASS_TBL CT LEFT JOIN TEACHER_TBL TT ON CT.TEACHER_ID = TT.TEACHER_ID 
   WHERE CT.CLASS_ID = #{classID}; 
</select>
Copy after login

其中的teacherResultMap请见上面TeacherMapper.xml文件部分内容中。

collection聚集

聚集元素用来处理“一对多”的关系。需要指定映射的Java实体类的属性,属性的javaType(一般为ArrayList);列表中对象的类型ofType(Java实体类);对应的数据库表的列名称;

不同情况需要告诉MyBatis 如何加载一个聚集。MyBatis 可以用两种方式加载:

1. select: 执行一个其它映射的SQL 语句返回一个Java实体类型。较灵活;

2. resultsMap: 使用一个嵌套的结果映射来处理通过join查询结果集,映射成Java实体类型。

例如,一个班级有多个学生。

首先定义班级中的学生列表属性:


private List<StudentEntity> studentList;
Copy after login

使用select实现聚集

用法和联合很类似,区别在于,这是一对多,所以一般映射过来的都是列表。所以这里需要定义javaType为ArrayList,还需要定义列表中对象的类型ofType,以及必须设置的select的语句名称(需要注意的是,这里的查询student的select语句条件必须是外键classID)。

ClassMapper.xml文件部分内容:


<resultMap type="ClassEntity" id="classResultMap"> 
  <id property="classID" column="CLASS_ID" /> 
  <result property="className" column="CLASS_NAME" /> 
  <result property="classYear" column="CLASS_YEAR" /> 
  <association property="teacherEntity" column="TEACHER_ID" select="getTeacher"/> 
  <collection property="studentList" column="CLASS_ID" javaType="ArrayList" ofType="StudentEntity" select="getStudentByClassID"/> 
</resultMap> 
 
<select id="getClassByID" parameterType="String" resultMap="classResultMap"> 
  SELECT * FROM CLASS_TBL CT 
  WHERE CT.CLASS_ID = #{classID}; 
</select>
Copy after login

StudentMapper.xml文件部分内容:


<!-- java属性,数据库表字段之间的映射定义 --> 
<resultMap type="StudentEntity" id="studentResultMap"> 
  <id property="studentID" column="STUDENT_ID" /> 
  <result property="studentName" column="STUDENT_NAME" /> 
  <result property="studentSex" column="STUDENT_SEX" /> 
  <result property="studentBirthday" column="STUDENT_BIRTHDAY" /> 
</resultMap> 
 
<!-- 查询学生list,根据班级id --> 
<select id="getStudentByClassID" parameterType="String" resultMap="studentResultMap"> 
  <include refid="selectStudentAll" /> 
  WHERE STCLASS_ID = #{classID} 
</select>
Copy after login

使用resultMap实现聚集

使用resultMap,就需要重写一个sql,left join学生表。


<resultMap type="ClassEntity" id="classResultMap"> 
  <id property="classID" column="CLASS_ID" /> 
  <result property="className" column="CLASS_NAME" /> 
  <result property="classYear" column="CLASS_YEAR" /> 
  <association property="teacherEntity" column="TEACHER_ID" resultMap="teacherResultMap"/> 
  <collection property="studentList" column="CLASS_ID" javaType="ArrayList" ofType="StudentEntity" resultMap="studentResultMap"/> 
</resultMap> 
 
<select id="getClassAndTeacherStudent" parameterType="String" resultMap="classResultMap"> 
  SELECT * 
   FROM CLASS_TBL CT 
      LEFT JOIN STUDENT_TBL ST 
       ON CT.CLASS_ID = ST.CLASS_ID 
      LEFT JOIN TEACHER_TBL TT 
       ON CT.TEACHER_ID = TT.TEACHER_ID 
   WHERE CT.CLASS_ID = #{classID}; 
</select>
Copy after login

其中的teacherResultMap请见上面TeacherMapper.xml文件部分内容中。studentResultMap请见上面StudentMapper.xml文件部分内容中。

discriminator鉴别器

有时一个单独的数据库查询也许返回很多不同(但是希望有些关联)数据类型的结果集。鉴别器元素就是被设计来处理这个情况的,还有包括类的继承层次结构。鉴别器非常容易理解,因为它的表现很像Java语言中的switch语句。

定义鉴别器指定了column和javaType属性。列是MyBatis查找比较值的地方。JavaType是需要被用来保证等价测试的合适类型(尽管字符串在很多情形下都会有用)。

下面这个例子为,当classId为20000001时,才映射classId属性。


<resultMap type="bjpowernodestudentmanagerdatamodelStudentEntity" id="resultMap_studentEntity_discriminator"> 
  <id property="studentId"    column="STUDENT_ID" javaType="String" jdbcType="VARCHAR"/> 
  <result property="studentName"    column="STUDENT_NAME" javaType="String" jdbcType="VARCHAR"/> 
  <result property="studentSex"    column="STUDENT_SEX" javaType="int" jdbcType="INTEGER"/> 
  <result property="studentBirthday"  column="STUDENT_BIRTHDAY" javaType="Date" jdbcType="DATE"/> 
  <result property="studentPhoto" column="STUDENT_PHOTO" javaType="byte[]" jdbcType="BLOB" typeHandler="orgapacheibatistypeBlobTypeHandler" /> 
  <result property="placeId"      column="PLACE_ID" javaType="String" jdbcType="VARCHAR"/> 
  <discriminator column="CLASS_ID" javaType="String" jdbcType="VARCHAR"> 
    <case value="20000001" resultType="bjpowernodestudentmanagerdatamodelStudentEntity" > 
      <result property="classId" column="CLASS_ID" javaType="String" jdbcType="VARCHAR"/> 
    </case> 
  </discriminator> 
</resultMap>
Copy after login

The above is the detailed content of Detailed introduction to resultmap of mybatis tutorial. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Roblox: Bubble Gum Simulator Infinity - How To Get And Use Royal Keys
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Nordhold: Fusion System, Explained
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Mandragora: Whispers Of The Witch Tree - How To Unlock The Grappling Hook
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1669
14
PHP Tutorial
1273
29
C# Tutorial
1256
24
Detailed explanation of the Set tag function in MyBatis dynamic SQL tags Detailed explanation of the Set tag function in MyBatis dynamic SQL tags Feb 26, 2024 pm 07:48 PM

Interpretation of MyBatis dynamic SQL tags: Detailed explanation of Set tag usage MyBatis is an excellent persistence layer framework. It provides a wealth of dynamic SQL tags and can flexibly construct database operation statements. Among them, the Set tag is used to generate the SET clause in the UPDATE statement, which is very commonly used in update operations. This article will explain in detail the usage of the Set tag in MyBatis and demonstrate its functionality through specific code examples. What is Set tag Set tag is used in MyBati

Detailed explanation of MyBatis cache mechanism: understand the cache storage principle in one article Detailed explanation of MyBatis cache mechanism: understand the cache storage principle in one article Feb 23, 2024 pm 04:09 PM

Detailed explanation of MyBatis caching mechanism: One article to understand the principle of cache storage Introduction When using MyBatis for database access, caching is a very important mechanism, which can effectively reduce access to the database and improve system performance. This article will introduce the caching mechanism of MyBatis in detail, including cache classification, storage principles and specific code examples. 1. Cache classification MyBatis cache is mainly divided into two types: first-level cache and second-level cache. The first-level cache is a SqlSession-level cache. When

Sharing optimization tips for batch Insert statements in MyBatis Sharing optimization tips for batch Insert statements in MyBatis Feb 22, 2024 pm 04:51 PM

MyBatis is a popular Java persistence layer framework that implements the mapping of SQL and Java methods through XML or annotations, and provides many convenient functions for operating databases. In actual development, sometimes a large amount of data needs to be inserted into the database in batches. Therefore, how to optimize batch Insert statements in MyBatis has become an important issue. This article will share some optimization tips and provide specific code examples. 1.Use BatchExecu

MyBatis Generator configuration parameter interpretation and best practices MyBatis Generator configuration parameter interpretation and best practices Feb 23, 2024 am 09:51 AM

MyBatisGenerator is a code generation tool officially provided by MyBatis, which can help developers quickly generate JavaBeans, Mapper interfaces and XML mapping files that conform to the database table structure. In the process of using MyBatisGenerator for code generation, the setting of configuration parameters is crucial. This article will start from the perspective of configuration parameters and deeply explore the functions of MyBatisGenerator.

Security First: Best Practices to Prevent SQL Injection in MyBatis Security First: Best Practices to Prevent SQL Injection in MyBatis Feb 22, 2024 pm 12:51 PM

As network technology continues to develop, database attacks are becoming more and more common. SQL injection is one of the common attack methods. Attackers enter malicious SQL statements into the input box to perform illegal operations, causing data leakage, tampering or even deletion. In order to prevent SQL injection attacks, developers must pay special attention when writing code, and when using an ORM framework such as MyBatis, they need to follow some best practices to ensure the security of the system. 1. Parameterized query Parameterized query is the anti-

Detailed explanation of MyBatis first-level cache: How to improve data access efficiency? Detailed explanation of MyBatis first-level cache: How to improve data access efficiency? Feb 23, 2024 pm 08:13 PM

Detailed explanation of MyBatis first-level cache: How to improve data access efficiency? During the development process, efficient data access has always been one of the focuses of programmers. For persistence layer frameworks like MyBatis, caching is one of the key methods to improve data access efficiency. MyBatis provides two caching mechanisms: first-level cache and second-level cache. The first-level cache is enabled by default. This article will introduce the mechanism of MyBatis first-level cache in detail and provide specific code examples to help readers better understand

In-depth understanding of MyBatis dynamic SQL tags: Trim tag function analysis In-depth understanding of MyBatis dynamic SQL tags: Trim tag function analysis Feb 21, 2024 pm 09:42 PM

MyBatis is a lightweight Java persistence layer framework that provides many convenient SQL statement splicing functions, among which dynamic SQL tags are one of its powerful features. In MyBatis, the Trim tag is a very commonly used tag, used to dynamically splice SQL statements. In this article, we will take a deep dive into the functionality of the Trim tag in MyBatis and provide some concrete code examples. 1. Introduction to Trim tag In MyBatis, the Trim tag is used to remove the generated S

Detailed explanation of the principle of MyBatis paging plug-in Detailed explanation of the principle of MyBatis paging plug-in Feb 22, 2024 pm 03:42 PM

MyBatis is an excellent persistence layer framework. It supports database operations based on XML and annotations. It is simple and easy to use. It also provides a rich plug-in mechanism. Among them, the paging plug-in is one of the more frequently used plug-ins. This article will delve into the principles of the MyBatis paging plug-in and illustrate it with specific code examples. 1. Paging plug-in principle MyBatis itself does not provide native paging function, but you can use plug-ins to implement paging queries. The principle of paging plug-in is mainly to intercept MyBatis

See all articles
Property

Description