Home  >  Article  >  Java  >  Detailed introduction to resultmap of mybatis tutorial

Detailed introduction to resultmap of mybatis tutorial

黄舟
黄舟Original
2017-09-02 10:34:551667browse

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>

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>

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>

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


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

association联合

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

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

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

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

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

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


private TeacherEntity teacherEntity;

使用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>

 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>

使用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>

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

collection聚集

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

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

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

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

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

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


private List<StudentEntity> studentList;

使用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>

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>

使用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>

其中的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>
Property

Description

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:
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