MyBatis Mapping File Tags

MyBatis Mapping File Tags

insert image description here

The mapping file should have the same name as the interface file.

ORM (Object Relationship Mapping) object-relational mapping.

The object represents the Java entity class object, the relationship represents the relational database, and the mapping represents the corresponding relationship between the two.

The following will summarize the commonly used tags of MyBatis XML mapping files:

1. Define the SQL statement

​ There are 4 tags in total, namely insert, delete, update, and select, corresponding to adding, deleting, modifying and checking. Among them, the select tag is used most frequently. The specific use is as follows:

The Mapper layer interface definition method is as follows:

public interface StudentMapper {
    
    
    Student findById(Integer id);
    List<Student> findAll();
}

The Mapper.XML mapping file is as follows:

<?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.exercise.dao.StudentMapper">
    <select id="fingById" resultType="com.exercise.entity.Student">
        <!-- Mybatis负责把SQL语句中的#{}部分替换成“?”占位符,在#{}内部还是要声明一个见名知意的名称 -->
        select * from t_student where id = #{id}
    </select>
    
    <select id="findAll" resultType="com.exercise.entity.Student">
       select * from user
    </select>
</mapper>

illustrate:

  • mapper is the root label, and the namespace attribute is set to the full class name of the interface.
  • The id attribute in the label is the method name of the interface method, and the id is unique, that is, it marks a SQL statement.
  • The resultType attribute in the tag is the return value type of the interface method, and the format is the full class name. If it is a collection type, write its generic full class name.
  • The parameterType attribute in the tag is the parameter type of the interface method, and the format is the full class name. If it is a collection type, write the full class name of its generic type.
  • When the parameter/return value type is a basic data type/wrapper class/String and other types, we can write the full class name or an alias. The built-in type aliases of MyBatis are as follows:
type of mapping alias type of mapping alias
byte _byte String string
long _long Byte byte
short _short Long long
int _int Short short
int _integer Integer integer\int
double _double Double double
float _float Float float
boolean _boolean Boolean boolean
Map map Date date
HashMap hashmap BigDecimal decimal
List list BigDecimal bigdecimal
ArrayList arraylist Object object
Collection collection Iterator iterator

2. Custom mapping relationship

​ MyBatis can encapsulate the database result set into an object because the column names of the result set are the same as the object property names. When the Entity attribute name is inconsistent with the database column name, MyBatis cannot automatically complete the mapping

relation. At this point there are two solutions:

  1. The query field of the SQL statement is given the same alias as the Entity property.
  2. Customize the mapping relationship, use <resultMap>the label to define the corresponding relationship, and then refer to the corresponding relationship in the subsequent SQL statement

In actual development, the second method is mostly used, as follows:

<resultMap id="selectStudentMap" type="com.exercise.entity.Student">
    <id column="id" property="studentId"/>
    <result column="name" property="studentName"/>
    <result column="class" property="studentClass"/>
</resultMap>

<select id="selectStudent" resultMap="selectStudentMap">
    select id,name,class from t_student where id=#{id}
</select>

illustrate:

  • The id attribute in the resultMap tag is the name of the custom map, and the type attribute is the object of the custom map (usually a DTO or VO in actual development).
  • The id tag sets the corresponding relationship between the primary key column and the primary key attribute, the column attribute represents the database field name, and the property attribute represents the Java entity class attribute name.
  • The result tag sets the relationship between ordinary fields and Java entity class attributes, and the column and property attributes are consistent with the id tag.

3. Dynamic SQL splicing

1. if tag

​ Using <if>tags allows us to selectively add fragments of SQL statements. The Sql fragment in the tag will only be added after the condition is met, as follows:

<select id="selectByCondition" parameterType="com.exercise.entity.Student" resultType="com.exercise.entity.Student">
   	select * from t_student
    <where>
        <if test="id != null">
           id = #{id}
        </if>
        <if test="name != null and name.length() != 0">
           and name like concat('%',#{name},'%')
        </if>
        <if test="class != null and class.length() != 0">
           and class = #{class}
        </if>
    </where>
</select>

illustrate:

  • The test attribute in the if tag represents the condition, if it is met, the SQL fragment will be added, otherwise it will not be added.
  • The condition in the if can directly obtain the attribute value of the parameter Entity through the attribute name, and the value can call methods, such as String.length(), but cannot access the fields of the database table.
  • Conditions in if cannot use &&/||, but should use and/or.

2. foreach tag (important)

​Tags<foreach> can traverse collections or arrays, which is very practical in actual development. It mainly has the following properties:

  • collection property: the collection object to traverse
  • item attribute: Indicates the element obtained by this traversal (set the name for easy reference later). It indicates each element when traversing List, Set, and array, and indicates the value of the key-value pair when traversing Map .
  • index attribute: indicates the index of the traversal when traversing the List and array , and indicates the key of the key-value pair when traversing the Map .
  • separator attribute: traverse the separator between each element.
  • open attribute: the prefix of the concatenated string.
  • close attribute: the suffix of the concatenated string.

Here is an actual scenario encountered, single-table query (table, query field, query field value, and additional conditions are all dynamically obtained), specific examples are as follows:

Dao layer interface methods are as follows:

/**
 * 单表查询
 * @param tableName                 表名
 * @param queryPrimaryKeyList       查询主键集合(注:设计集合的形式是因为还有多表联查)
 * @param queryPrimaryKeyValueList  查询主键集合(附带value)
 * @param queryFieldList            查询字段集合(注:查询字段里面不包含查询主键)
 * @param extraFieldList            附加条件集合
 * @return
 */
List<Map<String,Object>> queryDataResultSingleTable(@Param("tableName") String tableName,
                                                    @Param("queryPrimaryKeyList") List<String> queryPrimaryKeyList,
                                                    @Param("queryPrimaryKeyValueList") List<Map<String, Object>> queryPrimaryKeyValueList,
                                                    @Param("queryFieldList") List<String> queryFieldList,
                                                    @Param("extraFieldList") List<ExtraFieldDTO> extraFieldList);

The Mapper.XML mapping file is as follows:

<select id="queryDataResultSingleTable" resultType="map">
    SELECT
    <foreach collection="queryPrimaryKeyList" item="queryPrimaryKey" index="index" separator=",">
        ${queryPrimaryKey}
    </foreach>,
    <foreach collection="queryFieldList" item="queryField" index="index" separator=",">
        ${queryField}
    </foreach>
    FROM
    ${tableName}
    <where>
        <foreach collection="queryPrimaryKeyValueList" item="queryPrimaryKey" >
            <foreach collection="queryPrimaryKey.entrySet()" item="value" index="key">
                OR ${key} = #{value}
            </foreach>
        </foreach>
        <if test="extraFieldList!= null and extraFieldList.size()>0 ">
            <foreach collection="extraFieldList" item="extraField">
                <foreach collection="extraField.entrySet()" item="value" index="key">
                    AND ${key} like concat('%',#{value,jdbcType=VARCHAR},'%')
                </foreach>
            </foreach>
        </if>
    </where>
</select>

3. choose/when/otherwise tags

​ These three labels represent multi-conditional branching, that is, only one of the multiple branching conditions is executed. Similar to the switch...case statement in Java, <choose>similar to the switch keyword, <when>similar to the case keyword, <otherwise>similar to the default keyword. The execution process is as follows:

  • Conditions are judged sequentially from top to bottom.
  • It is judged that the first branch that satisfies the condition will be executed.
  • After being executed, the following branches will not be executed.
  • If all the when branches are not satisfied, execute the statements in the otherwise branch.

Specific examples are as follows:

<!-- 含义为名字长度<3时使用模糊查询,名字长度>=3并且<5时使用精确查询,否则查询id为1的用户 -->
<select id="selectByCondition" resultType="com.exercise.entity.Student" parameterType="com.exercise.entity.Student">
   select * from t_student
    <where>
        <choose>
            <when test="name.length()&lt; 3">
               name like concat('%',#{value},'%')
            </when>
            <when test="name.length()&lt; 5">
                name = #{name}
            </when>
            <otherwise>
               	id = 1
            </otherwise>
        </choose>
    </where>
</select>

Note : Try not to use some special characters in the MyBatis mapping file, such as: <, >, etc. We can use the entity of the symbol to represent, as follows:

symbol entity
< &lt;
> &gt;
& &amp;
&apos;
‘’ &quot;

4. Formatted output

1. where tag

​Tags<where> can automatically remove redundant and and or in the tag body . This tag is generally used in conjunction with the if tag. Just imagine, if we use the if tag, we need to add the where keyword. When all the if conditions are not satisfied or the second condition is satisfied, the SQL statement we output is an error. of. Since the where tag has been used in the previous tag example, no specific example will be given here.

2. set tag

​ In actual development, when updating an entity class object, it is often not to update all fields, but to update some fields changed by the user. <set>The label is used in the update statement. With the help of <if>the label , only the fields with specific values ​​can be updated. <set>Labels will automatically add the set keyword, and dynamically remove redundant commas at both ends. Specific examples are as follows:

<update id="updateById" parameterType="com.exercise.entity.Student">
   update user
    <set>
        <if test="name != null and name.length() > 0">
           name = #{name},
        </if>
        <if test="class != null and class.length() > 0">
           class = #{class},
        </if>
    </set>
    <where>
       	id = #{id}
    </where>
</update>

3. trim label

​The label<trim> can control whether certain characters are included at both ends of the condition part, and it mainly has the following attributes:

  • prefix attribute: specify the prefix to be added dynamically
  • suffix attribute: specify the suffix to be added dynamically
  • prefixOverrides attribute: specify the prefix to be dynamically removed, use "|" to separate possible multiple values
  • suffix Overrides attribute: specify the suffix to be dynamically removed, use "|" to separate possible multiple values

Five, configure the relationship

1. Association tag

​ Use <association>tags to configure a one-to-one relationship, which has the following attributes, as follows:

  • property attribute: the property name used when referencing
  • javaTyoe attribute: the corresponding full class name

Specific examples are as follows:

<resultMap id="studentMap" type="com.exercise.entity.Student">
    <id column="id" property="id"></id>
    <result column="name" property="name"></result>
    <!-- 一对一对象列 property:属性名 javaType:对象类型-->
    <association property="class" javaType="com.exercise.entity.Class">
        <id column="class_id" property="classId"></id>
        <result column="class_name" property="className"></result>
    </association>
</resultMap>

<!-- 多表查询,级联查询学生和其班级 -->
<select id="findAll" resultMap="studentMap">
   select * from t_student left join t_class on student.classId = class.class_id
</select>

2. collection tag

​ Use <collection>tags to configure one-to-many associations, which have the following attributes, as follows:

  • property attribute: the attribute name of the "many" end of the association
  • ofTyoe attribute: the type of elements in the collection attribute

Specific examples are as follows:

<resultMap id="classesMap" type="com.exercise.entity.Class">
    <id column="class_id" property="classId"></id>
    <result column="class_name" property="className"></result>
    <!-- 集合列 property:属性名 ofType:集合的泛型 -->
    <collection property="studentList" ofType="com.exercise.entity.Student">
        <id column="id" property="id"></id>
        <result column="name" property="name"></result>
    </collection>
</resultMap>

<!-- 多表查询,级联查询班级和它的学生 -->
<select id="selectAllStudent" resultMap="classesMap">
    select * from t_class left join t_student on class.class_id = student.classId;
</select>

6. Define constants and references

​Tags<sql> can be used to define reusable SQL fragments, which are then imported via <include>the tag . The specific use is as follows:

<sql id="selectAllField">
   	select id as studentId, name as studentName
</sql>

<select id="selectById" resultType="com.exercise.entity.Student">
    <include refid="selectAllField"></include>
   	from t_student where id = #{id}
</select>

Guess you like

Origin blog.csdn.net/m0_53067943/article/details/128320027