Detailed explanation of Mybatis tags

Mybatis tags

insert image description here

1. Define the sql statement

1.1 select tag

<select id="selectById" resultMap="BaseResultMap" parameterType="Object">
    select * from user where id=#{
    
    id}
</select>

id: unique identification
parameterType: parameter type, the full path or alias of the parameter passed to this statement, for example: com.promote.User
resultMap: return result type (resultMap and resultType cannot be used at the same time). Note: If it is a collection, fill in the generic type of the collection.

1.2 insert tag

<insert id="insert" parameterType="Object">
	insert into user
	<trim  prefix="(" suffix=")" suffixOverrides="," >
		<if test="name != null"> NAME, </if>
	</trim>
	<trim prefix="values(" suffix=")" suffixOverrides="," >
		<if test="name != null  ">  #{
    
    name},  </if>
	</trim>
</insert>

id: Unique identifier
parameterType: The parameter type passed to the statement

1.3 delete tag

<delete id="deleteById" parameterType="Object">
    delete from user where id=#{
    
    id}
</delete>

id: uniquely identifies
parameterType: the parameter type passed to the statement

1.4 update tag

<update id="update" parameterType="Object">
	update user set 
		<if test="name != null"> NAME = #{
    
    name},</if>
		<if test="sex != null"> SEX = #{
    
    sex} </if>
	where ID = #{
    
    id}
</update>

id: uniquely identifies
parameterType: the parameter type passed to the statement

2. Configure the returned result set

resultMap

Function: Establish the mapping relationship between the sql query result field and the entity class attribute, and convert the query result set into a java object.

<resultMap id="demo" type="com.promote.model.Food">
    <id property="id" column="id" />
    <result column="food" property="foodName" />
    <result column="number" property="number" />
</resultMap>

    // 查询是resultMap 通过id 引用对应的resutMap
<select id="selectFood" resultMap="demo" parameterType="Object">
	select * from food where id = #{
    
    id}
</select>

Main attribute:

id: Change the unique identifier of resultMap

type: the class name corresponding to the return value

Subproperties:

id: used to set the mapping relationship between the primary key field and the entity attribute

result: The user sets the mapping relationship between ordinary fields and entity attributes

Attributes:

column: corresponds to the field name in the database

property: the attribute name of the corresponding entity class

3. Dynamic sql splicing

3.1 if tag

The if tag is usually used in WHERE statement, UPDATE statement, and INSERT statement. By judging the parameter value, it is determined whether to use a certain query condition, whether to update a certain field, or whether to insert the value of a certain field.

<if test="name != null and name != ''">
     and NAME = #{
    
    name}
</if>

3.2 foreach tag

The foreach tag is mainly used to build in conditions, which can iterate collections in SQL. It is also commonly used in operations such as batch deletion and addition.

<select id="selectIn" resultMap="BaseResultMap">
    select name,hobby 
       from student 
       where id in
   <foreach item="item" index="index" collection="listdemo" open="(" separator="," close=")">
        #{item}
   </foreach>
</select>

collection: Specify the collection attributes (list, array, map) in the input object

item: an alias for each element during iteration

index: identifies the position of each iteration

open: prefix

close: suffix

separator: separator, the separator between each element when iterating

3.3 choose label

MyBatis provides the choose element to determine whether the conditions in when are true in order. If one is true, choose ends. When all when conditions in choose are not satisfied, execute the sql in otherwise. Similar to Java's switch statement, choose is switch, when is case, and otherwise is default.

If is the relationship with (and), and choose is the relationship of or (or).

<select id="getUserListChoose" parameterType="user" resultMap="BaseResultMap">     
    SELECT * from user WHERE 1=1        
        <choose>     
            <when test="Name!=null and student!='' ">     
                   AND name LIKE CONCAT(CONCAT('%', #{
    
    student}),'%')      
            </when>     
            <when test="hobby!= null and hobby!= '' ">     
                    AND hobby = #{
    
    hobby}      
            </when>                   
            <otherwise>     
                    AND AGE = 15  
            </otherwise>     
        </choose>      
</select> 

4. Formatted output

4.1 where tag

When there are many if tags, splicing may be wrong, as in the following code:

<select id="getUserListWhere" parameterType="Object" resultMap="BaseResultMap">     
    SELECT * from user      
        WHERE      
        <if test="name!=null and name!='' ">     
            NAME LIKE CONCAT(CONCAT('%', #{
    
    name}),'%')      
        </if>     
        <if test="sex!= null and sex!= '' ">     
            AND sex = #{
    
    sex}      
        </if>     
</select> 

When the name value is null, the query statement will appear "WHERE AND". To solve this situation, in addition to changing "WHERE" to "WHERE 1=1", you can also use the where tag.

The "where" tag will know to insert a 'where' if there is a return value in the tag it contains . Also, if a tag returns something that starts with AND or OR, it will strip it out .

<select id="getUserListWhere" parameterType="Object" resultMap="BaseResultMap">     
    SELECT * from user      
       <where>   
         <if test="name!=null and name!='' ">     
            NAME LIKE CONCAT(CONCAT('%', #{
    
    name}),'%')      
         </if>     
         <if test="sex!= null and sex!= '' ">     
            AND sex = #{
    
    sex}      
         </if>   
       </where>        
</select> 

4.2 set label

Function: After modifying with the set+if tag, if an item is null, it will not be updated, but the original value of the database will be kept.

<update id="updateUser" parameterType="Object">     
    UPDATE user      
    <set>     
        <if test="name!=null and name!='' ">     
            name = #{
    
    name},      
        </if>     
        <if test="sex!=null and sex!='' ">     
            sex = #{
    
    sex},      
        </if> 
        <if test="age!=null and age!='' ">     
            age = #{
    
    age}    
        </if>     
    </set>     
    WHERE ID = #{
    
    id};      
</update>  

4.3 trim label

Formatted output can be achieved by setting or ignoring the prefix and suffix through the trim tag

<update id="updateById" parameterType="Object">
    update user set 
          <trim  suffixOverrides="," > 
            <if test="name != null  ">
                name=#{
    
    name},
            </if>
            <if test="sex != null  ">
                sex=#{
    
    sex},
            </if>
          </trim> where id=#{
    
    id}
  </update>

Attributes:

prefix: The prefix overrides and augments its content.

suffix: The suffix overrides and augments its content. When the values ​​in the trim tag are not all empty, add the prefix of prefisx and the suffix of suffix.

prefixOverrides: The condition for prefix judgment. ignore the first

suffixOverrides: Conditions for suffix judgment. As above, suffixOverrides="," will ignore the last ","

5. Define constants and references

5.1 sql tag

When the query fields or query conditions of multiple types of query statements are the same, they can be defined as constants for easy calling. In order to clear the structure, the sql statement can also be decomposed.

//定义常量
<sql id="Base_Column_List">
	id,name,sex,age
</sql>

5.2 include tag

user reference constant

 <select id="selectAll" resultMap="BaseResultMap">
     SELECT
     <include refid="Base_Column_List" />
     FROM user
 </select>

Guess you like

Origin blog.csdn.net/weixin_40307206/article/details/108848914
Recommended