Detailed Java MyBatis framework SQL statement mapping part

  • 2020-05-07 19:50:05
  • OfStack

1.resultMap
The
SQL mapping XML file is where all sql statements are placed. You need to define 1 workspace, which is generally defined as the path of the corresponding interface class. After writing the SQL statement mapping file, you need to refer to it in the MyBAtis configuration file mappers tag, for example:


<mappers> 
  <mapper resource="com/liming/manager/data/mappers/UserMapper.xml" /> 
  <mapper resource="com/liming/manager/data/mappers/StudentMapper.xml" /> 
  <mapper resource="com/liming/manager/data/mappers/ClassMapper.xml" /> 
  <mapper resource="com/liming/manager/data/mappers/TeacherMapper.xml" /> 
</mappers> 

 
When the Java interface is in a relative path to the XML file, it may not be declared in mappers of the myBatis configuration file.

SQL maps the primary elements of XML file 1:

(1). cache wok configures the cache for the given pattern
(2). cache-ref, which refers to a cache from another mode
This is the most complex yet powerful element. It describes how to load an object from a result set
(4). sql: an SQL block that can be reused by other statements
(5). insert and the INSERT statement
(6).update and map UPDATE statements
(7). delete - mapping DELEETE statement
(8). select  -  maps SELECT statements

1.1 resultMap
resultMap is the most important and powerful element in MyBatis. You can save 90% of your code from calling the result set with JDBC, or you can do a lot of things that JDBC doesn't support. In reality, it can take thousands of lines of code to write a complex statement that corresponds to an interactive mapping. The purpose of ResultMaps is to make such a simple statement without any redundant result mapping, and to make more complex statements without any need for anything other than an absolutely necessary statement describing the relationship.
resultMap attribute: type is java entity class; id for this resultMap logo.
 
resultMap can be set to map:

(1). constructor: the constructor that reflects the result to an instantiated class
Parameters of a) idArg and ID; Mark the result set as ID for global invocation
b) arg reflects the usual result of the constructor

(2). id, the result set is marked as ID for global invocation

(3). result is reflected to the normal result of the JavaBean attribute

(4). Combination of complex types of association; The type of multiple result composition
a) nested result mappings and resultMap are nested associations themselves and can also be referenced to one other

(5). collection complex type collection a collection of complex types

(6). The collection of nested result mappings and resultMap can also be referenced to one other

(7). discriminator wok USES one result value to determine which resultMap to use
a) case is a result map of some values of case
The i. nested result mappings situation is itself a result map, so you can include some of the same elements, or you can refer to an external resultMap.
 
1.1.1 id, result
id and result are the simplest mappings. id is the primary key mapping. Mapping of result other basic database table fields to entity class properties.
The simplest example:


<resultMap type="liming.student.manager.data.model.StudentEntity" 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="org.apache.ibatis.type.BlobTypeHandler" /> 
</resultMap> 

 
id, result statement properties configuration details:

属性

描述

property

需要映射到JavaBean 的属性名称。

column

数据表的列名或者标签别名。

javaType

1个完整的类名,或者是1个类型别名。如果你匹配的是1个JavaBean,那MyBatis 通常会自行检测到。然后,如果你是要映射到1个HashMap,那你需要指定javaType 要达到的目的。

jdbcType

数据表支持的类型列表。这个属性只在insert,update delete 的时候针对允许空的列有用。JDBC 需要这项,但MyBatis 不需要。如果你是直接针对JDBC 编码,且有允许空的列,而你要指定这项。

typeHandler

使用这个属性可以覆写类型处理器。这项值可以是1个完整的类名,也可以是1个类型别名。


Type JDBC supported
            for future reference, MyBatis supports the following JDBC types by JdbcType enumeration:
BIT, FLOAT, CHAR, TIMESTAMP, UNDEFINED, TINYINT, REAL, VARCHAR DECIMAL, TIME, NULL, CURSOR
 
1.1.2 constructor
when we use id and result, we need to define the attributes of the java entity class to map to the fields of the database table. This is done using JavaBean. Of course, we can also use entity class constructors to map the values, which are assigned by the order in which the constructor arguments are written. Limited functionality with construcotr (for example, cascading queries with collection). The above functions implemented by id and result can be changed to:


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

 
Of course, we need to define the StudentEntity entity class constructor:


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

1.1.3 association union
The
union element is used to handle one-to-one relationships. You need to specify the properties of the mapped Java entity class, and javaType of the properties (usually recognized by MyBatis itself). The column name of the corresponding database table. If you want to override it to return the value of the result, you need to specify typeHandler.
Different situations need to tell MyBatis how to load a union. MyBatis can be loaded in two ways:
(1). select: the SQL statement that executes 1 other mapping returns 1 Java entity type. More flexible;
(2). resultsMap: a nested result map is used to process the query result set by join, mapped to Java entity type.
 
For example, one class corresponds to one head teacher.
  first defines the class teacher's attributes:


private TeacherEntity teacherEntity; 

 
1.1.3.1 USES select for federation
Example: the class entity class has the property of the head teacher. When a class entity is obtained through association, the head teacher entity is mapped out.
  can thus directly reuse the query teacher defined in TeacherMapper.xml according to its ID select statement. There is no need to modify the written SQL statement, just modify resultMap directly.

  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 CT.CLASS_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> 

1.1.3.2 USES resultMap for federation
  and the above same function, query the class, at the same time query the head teacher. resultMap (as defined in xml of teacher) should be added to association, sql should be added to sql (refer to left join teacher table), select of teacher is not needed.

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

For teacherResultMap, please see the TeacherMapper.xml file section above.

1.1.4 collection aggregation
The
aggregation element is used to handle "1 to many" relationships. You need to specify the attributes of the mapped Java entity class, javaType of the attribute (1 is ArrayList); ofType (Java entity class); The column name of the corresponding database table;
Different situations need to tell MyBatis how to load a cluster. MyBatis can be loaded in two ways:
(1). select: an SQL statement that executes one other mapping returns one Java entity type. More flexible;
(2). resultsMap: a nested result map is used to process the query result set by join, mapped to Java entity type.
For example, a class has more than one student.
First, define the student list attribute in the class:
private List < StudentEntity > studentList;  
1.1.4.1 USES select for aggregation
The usage of
  is very similar to that of union, except that this is 1 to many, so 1 maps to a list. So you need to define javaType as ArrayList, you also need to define the type of object in the list, ofType, and the statement name of select that you must set (note that the select statement condition for the query student here must be foreign key 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 Properties, mapping definitions between database table fields  --> 
<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> 
 
<!--  Query students list According to the class id --> 
<select id="getStudentByClassID" parameterType="String" resultMap="studentResultMap"> 
  <include refid="selectStudentAll" /> 
  WHERE ST.CLASS_ID = #{classID} 
</select> 

1.1.4.2 aggregation using resultMap
  USES resultMap to rewrite one sql, left join student table.


<resultMap type="liming.student.manager.data.model.StudentEntity" 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="org.apache.ibatis.type.BlobTypeHandler" /> 
</resultMap> 
0

 
For teacherResultMap, see the TeacherMapper.xml file section above. See studentResultMap in the StudentMapper.xml file section above.
1.1.5discriminator discriminator
Sometimes a single database query may return many different (but hopefully related) result sets of data types. The discriminator element is designed to handle this situation, as well as the inheritance hierarchy that includes the class. The discriminator is easy to understand because it behaves much like the switch statement in the Java language.
The definition discriminator specifies the column and javaType attributes. The column is where MyBatis looks for the comparison value. JavaType is the appropriate type that needs to be used to ensure the equivalence test (although strings can be useful in many cases).
The following example maps the classId attribute when classId is 20000001.


<resultMap type="liming.student.manager.data.model.StudentEntity" 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="org.apache.ibatis.type.BlobTypeHandler" /> 
  <result property="placeId"      column="PLACE_ID" javaType="String" jdbcType="VARCHAR"/> 
  <discriminator column="CLASS_ID" javaType="String" jdbcType="VARCHAR"> 
    <case value="20000001" resultType="liming.student.manager.data.model.StudentEntity" > 
      <result property="classId" column="CLASS_ID" javaType="String" jdbcType="VARCHAR"/> 
    </case> 
  </discriminator> 
</resultMap> 

2. Add, delete, change, check, parameters, cache

2.1 select
1 select element is very simple. Such as:


<!--  Query students according to id --> 
<select id="getStudent" parameterType="String" resultMap="studentResultMap"> 
  SELECT ST.STUDENT_ID, 
        ST.STUDENT_NAME, 
        ST.STUDENT_SEX, 
        ST.STUDENT_BIRTHDAY, 
        ST.CLASS_ID 
     FROM STUDENT_TBL ST 
     WHERE ST.STUDENT_ID = #{studentID} 
</select> 

This statement is called 'getStudent', has an String parameter, and returns an object of type StudentEntity.
Note that the parameter is identified as: #{studentID}.
 
select statement properties configuration details:

属性 描述 取值 默认
id 在这个模式下唯1的标识符,可被其它语句引用
parameterType 传给此语句的参数的完整类名或别名
resultType 语句返回值类型的整类名或别名。注意,如果是集合,那么这里填写的是集合的项的整类名或别名,而不是集合本身的类名。(resultType 与resultMap 不能并用)
resultMap 引用的外部resultMap 名。结果集映射是MyBatis 中最强大的特性。许多复杂的映射都可以轻松解决。(resultType 与resultMap 不能并用)
flushCache 如果设为true,则会在每次语句调用的时候就会清空缓存。select 语句默认设为false true|false false
useCache 如果设为true,则语句的结果集将被缓存。select 语句默认设为false true|false false
timeout 设置驱动器在抛出异常前等待回应的最长时间,默认为不设值,由驱动器自己决定
true|false false
timeout 设置驱动器在抛出异常前等待回应的最长时间,默认为不设值,由驱动器自己决定 正整数 未设置
fetchSize 设置1个值后,驱动器会在结果集数目达到此数值后,激发返回,默认为不设值,由驱动器自己决定 正整数 驱动器决定
statementType statement,preparedstatement,callablestatement。
预准备语句、可调用语句
STATEMENT
PREPARED
CALLABLE
PREPARED
resultSetType forward_only,scroll_sensitive,scroll_insensitive
只转发,滚动敏感,不区分大小写的滚动
FORWARD_ONLY
SCROLL_SENSITIVE
SCROLL_INSENSITIVE
驱动器决定

2.2 insert
  1 simple insert statement:


<resultMap type="liming.student.manager.data.model.StudentEntity" 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="org.apache.ibatis.type.BlobTypeHandler" /> 
</resultMap> 
3

insert can be used to automatically generate the primary key policy supported by the database, set useGeneratedKeys= "true", then set keyProperty to the corresponding column, and you are done. For example, StudentEntity above USES auto-generated to generate the primary key for the id column. The following example USES mysql database nextval('student') as a custom function to generate 1 key.


<resultMap type="liming.student.manager.data.model.StudentEntity" 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="org.apache.ibatis.type.BlobTypeHandler" /> 
</resultMap> 
4
insert statement properties configuration details:
属性 描述 取值 默认
id 在这个模式下唯1的标识符,可被其它语句引用
parameterType 传给此语句的参数的完整类名或别名
flushCache 如果设为true,则会在每次语句调用的时候就会清空缓存。select 语句默认设为false true|false false
useCache 如果设为true,则语句的结果集将被缓存。select 语句默认设为false true|false false
timeout 设置驱动器在抛出异常前等待回应的最长时间,默认为不设值,由驱动器自己决定
true|false false
timeout 设置驱动器在抛出异常前等待回应的最长时间,默认为不设值,由驱动器自己决定 正整数 未设置
fetchSize 设置1个值后,驱动器会在结果集数目达到此数值后,激发返回,默认为不设值,由驱动器自己决定 正整数 驱动器决定
statementType statement,preparedstatement,callablestatement。
预准备语句、可调用语句
STATEMENT
PREPARED
CALLABLE
PREPARED
useGeneratedKeys

告诉MyBatis 使用JDBC 的getGeneratedKeys 方法来获取数据库自己生成的主键(MySQL、SQLSERVER 等

关系型数据库会有自动生成的字段)。默认:false

true|false false
keyProperty

标识1个将要被MyBatis 设置进getGeneratedKeys 的key 所返回的值,或者为insert 语句使用1个selectKey

子元素。


selectKey statement properties configuration details:
属性 描述 取值
keyProperty selectKey 语句生成结果需要设置的属性。
resultType 生成结果类型,MyBatis 允许使用基本的数据类型,包括String 、int类型。
order 可以设成BEFORE 或者AFTER,如果设为BEFORE,那它会先选择主键,然后设置keyProperty,再执行insert语句;如果设为AFTER,它就先运行insert 语句再运行selectKey 语句,通常是insert 语句中内部调用数据库(像Oracle)内嵌的序列机制。 BEFORE
AFTER
statementType 像上面的那样, MyBatis 支持STATEMENT,PREPARED和CALLABLE 的语句形式, 对应Statement ,PreparedStatement 和CallableStatement 响应 STATEMENT
PREPARED
CALLABLE

2.3 update, delete
1 simple update:


<resultMap type="liming.student.manager.data.model.StudentEntity" 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="org.apache.ibatis.type.BlobTypeHandler" /> 
</resultMap> 
5

  1 simple delete:


<resultMap type="liming.student.manager.data.model.StudentEntity" 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="org.apache.ibatis.type.BlobTypeHandler" /> 
</resultMap> 
6

 
update, delete statement property configuration details:

属性 描述 取值 默认
id 在这个模式下唯1的标识符,可被其它语句引用
parameterType 传给此语句的参数的完整类名或别名
flushCache 如果设为true,则会在每次语句调用的时候就会清空缓存。select 语句默认设为false true|false false
useCache 如果设为true,则语句的结果集将被缓存。select 语句默认设为false true|false false
timeout 设置驱动器在抛出异常前等待回应的最长时间,默认为不设值,由驱动器自己决定
true|false false
timeout 设置驱动器在抛出异常前等待回应的最长时间,默认为不设值,由驱动器自己决定 正整数 未设置
fetchSize 设置1个值后,驱动器会在结果集数目达到此数值后,激发返回,默认为不设值,由驱动器自己决定 正整数 驱动器决定
statementType statement,preparedstatement,callablestatement。
预准备语句、可调用语句
STATEMENT
PREPARED
CALLABLE
PREPARED

 
2.4 sql
The
Sql element is used to define a reusable SQL statement segment that can be called by other statements. Such as:


<!--  reuse sql statements   The query student Table all fields  --> 
<sql id="selectStudentAll"> 
    SELECT ST.STUDENT_ID, 
          ST.STUDENT_NAME, 
          ST.STUDENT_SEX, 
          ST.STUDENT_BIRTHDAY, 
          ST.CLASS_ID 
       FROM STUDENT_TBL ST 
</sql> 

In this way, the direct reference can be used in select statement. Change the above select statement to:


<!--  Query students according to id --> 
<select id="getStudent" parameterType="String" resultMap="studentResultMap"> 
  <include refid="selectStudentAll"/> 
      WHERE ST.STUDENT_ID = #{studentID}  
</select> 

  2.5 parameters
                                     
            basic data types, String, int, date, etc.
              but with the basic data type, you can only provide one parameter, so you need to use Java entity class or Map type as the parameter type. Its properties can be obtained directly from #{}.
2.5.1 basic type parameters
  retrieves the list of students according to the time of enrollment:


<resultMap type="liming.student.manager.data.model.StudentEntity" 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="org.apache.ibatis.type.BlobTypeHandler" /> 
</resultMap> 
9

List<StudentEntity> studentList = studentMapper.getStudentListByClassYear(StringUtil.parse("2007-9-1")); 
for (StudentEntity entityTemp : studentList) { 
  System.out.println(entityTemp.toString()); 
} 

 

2.5.2 Java entity type parameter
  retrieves a list of students by name and gender. Use entity class as parameter:


<!--  Query students list . like The name, = Gender, parameters entity type  --> 
<select id="getStudentListWhereEntity" parameterType="StudentEntity" resultMap="studentResultMap"> 
  SELECT * from STUDENT_TBL ST 
    WHERE ST.STUDENT_NAME LIKE CONCAT(CONCAT('%', #{studentName}),'%') 
     AND ST.STUDENT_SEX = #{studentSex} 
</select> 


StudentEntity entity = new StudentEntity(); 
entity.setStudentName(" li "); 
entity.setStudentSex(" male "); 
List<StudentEntity> studentList = studentMapper.getStudentListWhereEntity(entity); 
for (StudentEntity entityTemp : studentList) { 
  System.out.println(entityTemp.toString()); 
} 

2.5.3 Map parameters
retrieves student lists by name and gender. Use Map as parameter:


<!--  Query students list . = Gender, parameters map type  --> 
<select id="getStudentListWhereMap" parameterType="Map" resultMap="studentResultMap"> 
  SELECT * from STUDENT_TBL ST 
   WHERE ST.STUDENT_SEX = #{sex} 
     AND ST.STUDENT_SEX = #{sex} 
</select> 


Map<String, String> map = new HashMap<String, String>(); 
map.put("sex", " female "); 
map.put("name", " li "); 
List<StudentEntity> studentList = studentMapper.getStudentListWhereMap(map); 
for (StudentEntity entityTemp : studentList) { 
  System.out.println(entityTemp.toString()); 
} 

Multi-parameter implementation of 2.5.4
If
wants to pass in more than one parameter, you need to add the @Param annotation to the interface's parameters. An example is given:
Interface writing:


public List<StudentEntity> getStudentListWhereParam(@Param(value = "name") String name, @Param(value = "sex") String sex, @Param(value = "birthday") Date birthdar, @Param(value = "classEntity") ClassEntity classEntity); 

 
SQL writing:


<!--  Query students list . like The name, = Gender, = Birthday, = Class, multi-parameter mode  --> 
<select id="getStudentListWhereParam" resultMap="studentResultMap"> 
  SELECT * from STUDENT_TBL ST 
  <where> 
    <if test="name!=null and name!='' "> 
      ST.STUDENT_NAME LIKE CONCAT(CONCAT('%', #{name}),'%') 
    </if> 
    <if test="sex!= null and sex!= '' "> 
      AND ST.STUDENT_SEX = #{sex} 
    </if> 
    <if test="birthday!=null"> 
      AND ST.STUDENT_BIRTHDAY = #{birthday} 
    </if> 
    <if test="classEntity!=null and classEntity.classID !=null and classEntity.classID!='' "> 
      AND ST.CLASS_ID = #{classEntity.classID} 
    </if> 
  </where> 
</select>

Make enquiries:


List<StudentEntity> studentList = studentMapper.getStudentListWhereParam("", "",StringUtil.parse("1985-05-28"), classMapper.getClassByID("20000002")); 
for (StudentEntity entityTemp : studentList) { 
  System.out.println(entityTemp.toString()); 
} 

2.5.5 string substitution method
By default, using the #{} syntax causes MyBatis to generate PreparedStatement properties and to use PreparedStatement parameters (=?). To set the value safely. Try to make these fast and safe, and use them often. But sometimes you might want to simply substitute the unchanged string into the SQL statement. For example, for ORDER BY, you might use ORDER BY ${columnName} but MyBatis does not modify or circumvent this string.
Note: it is not safe to receive and apply one user's input to an unchanged statement in this way. This allows the user to insert broken code, so either ask the field not to allow the customer to enter it, or you check its validity directly.
2.6 cache cache

            MyBatis includes a strong, configurable, and customizable caching mechanism. The cache implementation of MyBatis 3 has many improvements, which are both robust and easier to configure. By default, caching is not turned on, except for session caching, which can improve performance and resolve global dependencies. To enable level 2 caching, you only need to add a simple 1 line to the SQL mapping file: < cache/ >

This simple statement works as follows:
(1). All select statements in the mapping file will be cached.
(2). All insert,update and delete statements in the mapping file will clear the cache.
(3). The cache is recycled using the "rarely used recently" algorithm
(4) the cache will not be cleared by the set time.
(5). Each cache can store 1024 lists or references to objects (regardless of the result of the query).
(6). The cache will be treated as a "read/write" cache, which means that the acquired object is not Shared and the caller is safe. There will be no other calls
(7). Or thread potential modification.
 
For example, create an FIFO cache to empty once in 60 seconds, store 512 object results or list references, and return read-only results. Because two callers modifying them in different threads can cause reference conflicts.


<cache eviction="FIFO" flushInterval="60000" size="512" readOnly="true"> 
</cache> 

 
You can also share the same cache configuration or instance in different namespaces. In this case, you can use cache-ref to refer to another cache.
< cache-ref namespace="com.liming.manager.data.StudentMapper"/ >  

Cache statement properties configuration details:

属性 说明 取值 默认值
eviction 缓存策略:
LRU - 最近最少使用法:移出最近较长周期内都没有被使用的对象。
FIFI- 先进先出:移出队列里较早的对象
SOFT - 软引用:基于软引用规则,使用垃圾回收机制来移出对象
WEAK - 弱引用:基于弱引用规则,使用垃圾回收机制来强制性地移出对象
LRU
FIFI
SOFT
WEAK
LRU
flushInterval 代表1个合理的毫秒总计时间。默认是不设置,因此使用无间隔清空即只能调用语句来清空。 正整数

不设置

size 缓存的对象的大小 正整数 1024
readOnly

只读缓存将对所有调用者返回同1个实例。因此都不能被修改,这可以极大的提高性能。可写的缓存将通过序列

化来返回1个缓存对象的拷贝。这会比较慢,但是比较安全。所以默认值是false。

true|false false