SoFunction
Updated on 2025-03-06

Mybatis commonly used tags

In daily development, tags in MyBatis play an important role. The following are some common tags and cases in the MyBatis framework:

1. <select> tag

&lt;!-- Query statement:resultType="" --&gt;
&lt;select  parameterType="int" resultType=""&gt;
    SELECT * FROM T_Users WHERE id = #{id}
&lt;/select&gt;
&lt;!-- Query statement:resultType=" --&gt;
&lt;select  resultType=""&gt;
   SELECT * FROM T_User WHERE USER_ID=#{userId,jdbcType=VARCHAR}
&lt;/select&gt;
&lt;!-- Query statement:parameterType="long" --&gt;
&lt;select  parameterType="long" resultType=""&gt;
    SELECT count(*)  FROM T_User_RECORD where user_id= #{userId,jdbcType=BIGINT}
&lt;/select&gt;
&lt;!-- Query statement:resultMap="templateMap" --&gt;
&lt;select  parameterType="int" resultMap="templateMap"&gt;
    SELECT * FROM T_Users WHERE id = #{id}
&lt;/select&gt;
&lt;!-- Query statement:resultType=" --&gt;
&lt;select  resultType=""&gt;
    SELECT count(*)  FROM T_USER_RECORD
&lt;/select&gt;
&lt;!-- Query statement:Add to&lt;if&gt; Label,uniongrammar,foreachgrammar --&gt;
&lt;select  parameterType="" resultType=""&gt;
    SELECT USER_ID,USER_NAME,DEPT_CODE,DEPT_NAME 
    FROM
    T_USER
    where STATUS = 'Y'
    &lt;if test="(flag_column== 'N'.toString()) "&gt;
        AND dept_leader = 'Y'
    &lt;/if&gt;
    UNION
    SELECT USER_ID,USER_NAME,DEPT_CODE,DEPT_NAME 
    FROM
    T_USER
    where STATUS = 'Y'
    &lt;if test="list!= null and  &gt; 0"&gt;
        AND
        &lt;foreach collection="list" index="index" item="item" open="(" separator="OR" close=")"&gt;
            T.USER_ID =  #{item,jdbcType=VARCHAR}
        &lt;/foreach&gt;
    &lt;/if&gt;) 
&lt;/select&gt;
&lt;!-- Execute stored procedures --&gt;
&lt;select  parameterType="String" useCache="false" statementType="CALLABLE"&gt;
   &lt;![CDATA[
    {call P_PROCEDURE(
    #{name,mode=IN,jdbcType=VARCHAR},
    #{age,mode=OUT,jdbcType=VARCHAR}
    )}
    ]]&gt;
&lt;/select&gt;

Explanation: This is the most basic tag used to execute SQL queries, according to the incomingidParameters retrieve user information from the users table.

2. <insert> tag

&lt;!-- Newuser --&gt;
&lt;insert  parameterType=""&gt;
    INSERT INTO users(name, email, created_at)
    VALUES (#{name,jdbcType=VARCHAR}, #{email,jdbcType=VARCHAR}, SYSDATE)
&lt;/insert&gt;
&lt;!-- Get from the sequencekey --&gt;
&lt;insert  parameterType=""&gt;
    &lt;selectKey   keyProperty="id" resultType="long" order="BEFORE" &gt;
        SELECT SEQ_USER.NEXTVAL FROM DUAL
    &lt;/selectKey&gt;
    INSERT INTO T_USER(ID,NAME,EMAIL,CREATE_TIME)
    VALUES(#{id,jdbcType=BIGINT},#{name,jdbcType=VARCHAR},#{email,jdbcType=VARCHAR},SYSDATE)
&lt;/insert&gt;
&lt;!-- MERGE INTOStatement --&gt;
&lt;insert  parameterType=""&gt;
	    MERGE INTO T_USER_WISHS W
	    USING (SELECT
	                #{id,jdbcType=BIGINT} ID,
	                #{name,jdbcType=VARCHAR} name,
	            FROM DUAL ) D
	    ON ( = )
	    WHEN MATCHED THEN UPDATE SET
	        = ,
	        W.CREATE_TIME = D.CREATE_TIME,
	        W.UPDATE_TIME = SYSDATE
	    WHEN NOT MATCHED THEN
	    INSERT  (
	        ,
	        ,
	        W.CREATE_TIME
	    )
	    VALUES(
	        ,
	        ,
	        SYSDATE
	    )
&lt;/insert&gt;   
&lt;!-- batchNew --&gt;
&lt;insert  parameterType=""&gt;
    INSERT INTO
    T_USER(ID,USER_ID,USER_NAME,CREATE_TIME)
    SELECT SEQ_USER.NEXTVAL,T.* FROM (
    &lt;foreach collection="list" item="item" index="index" separator="union all"&gt;
        SELECT
        #{,jdbcType=VARCHAR} USER_ID,
        #{,jdbcType=VARCHAR} USER_NAME,
        SYSDATE CREATE_TIME        
        FROM DUAL
    &lt;/foreach&gt;) T
&lt;/insert&gt; 
&lt;!-- batchmerge into --&gt;
&lt;insert &gt;
    MERGE INTO T_USER_SCORE S
    USING (
    &lt;foreach collection="list" item="item" index="index" separator="UNION ALL"&gt;
        SELECT
        #{,jdbcType=VARCHAR} USER_ID,
        #{,jdbcType=VARCHAR} USER_NAME,
        #{,jdbcType=VARCHAR} SCORE
        from dual
    &lt;/foreach&gt;
    ) D ON (S.STAFF_ID = D.STAFF_ID AND S.USER_NAME= D.USER_NAME)
    WHEN MATCHED THEN UPDATE SET
     = ,
    S.UPDATE_TIME = SYSDATE
    WHEN NOT MATCHED THEN
    INSERT (
    ,
    S.USER_ID,
    S.USER_NAME,
    ,
    S.CREATE_TIME)
    VALUES(
    SEQ_USER_SCORE.NEXTVAL,
    D.USER_ID,
    D.USER_NAME,
    ,
    SYSDATE)
&lt;/insert&gt;

3. <update> tag

&lt;!-- renewuser --&gt;
&lt;update  parameterType=""&gt;
    UPDATE users
    &lt;set&gt;
        name = #{name},
        email = #{email}
    &lt;/set&gt;
    WHERE id = #{id}
&lt;/update&gt;
&lt;!-- renewuser:use&lt;if&gt; --&gt;
&lt;update &gt;
    UPDATE T_USER_INFO
    SET AGE= #{age,jdbcType=VARCHAR},
    &lt;if test="finishFlag != null"&gt;
        FINISH_FLAG = #{age,jdbcType=VARCHAR},
    &lt;/if&gt;
    STATUS = #{status,jdbcType=VARCHAR}
    WHERE USER_ID = #{userId,jdbcType=VARCHAR}
&lt;/update&gt;
&lt;!-- renewuser:existwhere后面use&lt;if&gt; --&gt;
&lt;update  parameterType=""&gt;
    UPDATE T_USER 
    SET 
        UPDATE_TIME = SYSDATE,
    WHERE USER_FLAG='Y'
    &lt;if test="isFr != null and isFr== 'Y'.toString()"&gt;
        AND USER_ID = #{userId,jdbcType=VARCHAR}
    &lt;/if&gt;
&lt;/update&gt;
&lt;!-- renewuser:usesetLabel --&gt;
&lt;update  parameterType=""&gt;
    UPDATE T_USER
    &lt;set&gt;
        &lt;if test="status != null and status != ''"&gt;
            STATUS = #{status,jdbcType=VARCHAR},
        &lt;/if&gt;
        UPDATE_DATE = SYSDATE
    &lt;/set&gt;
    WHERE USER_ID = #{userId}
&lt;/update&gt;
&lt;!-- 批量renewuser --&gt;
&lt;update  &gt;
       &lt;foreach collection="list" item="item" open="begin" close=";end;" separator=";" index="index"&gt;
           UPDATE T_USER
               SET age= #{, jdbcType=VARCHAR}
           WHERE USER_ID = #{, jdbcType=VARCHAR}
       &lt;/foreach&gt;
&lt;/update&gt;
&lt;!-- 批量renewuser --&gt;
&lt;update &gt;
    &lt;foreach collection="items" item="item" separator=";" index="index"&gt;
        UPDATE ${} SET ${} = #{}
        WHERE ${} = #{}
    &lt;/foreach&gt;
&lt;/update&gt;

Explanation: According toidUpdate user records, onlynameandemailThe corresponding field will be updated only when it is not empty.

4. <delete> tag

&lt;!-- deleteuser --&gt;
&lt;delete  parameterType="int"&gt;
    DELETE FROM users WHERE id = #{id}
&lt;/delete&gt;

Explanation: According to the providedidDelete a record in the users table.

5. Dynamic SQL tags

a. <if>Label

<update >
    UPDATE users
    <set>
        <if test="name != null">name = #{name},</if>
        <if test="email != null">email = #{email}</if>
    </set>
    WHERE id = #{id}
</update>

Explanation: Only if the parameters passed innameoremailNot fornullThe corresponding fields will be updated only when .

b. <choose>, <when>, <otherwise>Label

<update >
    UPDATE users
    <set>
        <choose>
            <when test="operation == 'updateName'">
                name = #{newName}
            </when>
            <when test="operation == 'updateEmail'">
                email = #{newEmail}
            </when>
            <otherwise>
                status = #{newStatus}
            </otherwise>
        </choose>
    </set>
    WHERE id = #{userId}
</update>

Explanation: According to the type of operation passed in (operation) Select to update different fields.

c. <where>Label

<update >
    UPDATE users
    <set>
        last_login = NOW()
    </set>
    <where>
        <if test="id != null">id = #{id}</if>
        <if test="email != null">AND email = #{email}</if>
    </where>
</update>

explain:<where>Tags ensure that the WHERE conditional sentence syntax in the generated SQL is correct, and even if the condition is empty, there will be no unnecessary ones.AND

d. <foreach>Tags (looping through the collection)

<insert >
    INSERT INTO users(id, name)
    VALUES
    <foreach item="item" index="index" collection="list" separator=",">
        (#{}, #{})
    </foreach>
</insert>

Explanation: Batch insertion of users,listA parameter is a collection of multiple user objects.

6. Reference other SQL fragments

<sql >id, name, email</sql>
<select  resultType="">
    SELECT 
    <include ref/>
    FROM users
</select>

Explanation: Define reusable SQL fragments and pass<include>Label introduction.

7. <resultMap> tag

<resultMap  type="">
    <id property="id" column="user_id"/>
    <result property="name" column="username"/>
    <association property="address" javaType="">
        <id property="addressId" column="address_id"/>
        <result property="street" column="street"/>
    </association>
</resultMap>

Explanation: Used to map query results to Java objects, supporting complex mapping relationships such as one-to-one and one-to-many.

The above has compiled some very practical and commonly used tags in MyBatis. Hope it can help everyone.

statement

The copyright of this content belongs to CSDN-Little Wild Boar. Any unauthorized copying, reprinting, dissemination, sales, and gifting are illegal and legal liability will be pursued! ! !

This is the end of this article about the commonly used tags of Mybatis. For more related content of commonly used tags of Mybatis, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!