SoFunction
Updated on 2025-03-03

MyBatis  Label usage summary

Return the value directly to the object

<select  resultType="">
   SELECT Id,Title FROM User
</select>

If the field and attribute names are inconsistent, use resultMap to map

<resultMap  type="com.">
  <id column="stud_id" property="studId"  jdbcType="VARCHAR"/>
  <result column="user_name" property="name"  jdbcType="VARCHAR"/>
  <result column="email"  property="email"  jdbcType="VARCHAR" />
  <result column="phone"  property="phone"  jdbcType="VARCHAR" />
  <result column="status" property="status" jdbcType="INTEGER" />
  <result column="create_time" property="createTime" jdbcType="TIMESTAMP" />
</resultMap>
<select  resultMap="StudentResult" >
  SELECT * FROM STUDENTS
</select>

The query result of an entity references another entity is returned

<resultMap type="Course" >
  <id column="course_id" property="courseId"/>
  <result column="name" property="name"/>
  <result column="description" property="description"/>
  <result column="start_date" property="startDate"/>
  <result column="end_date" property="endDate"/>
</resultMap>
<resultMap type="Tutor" >
  <id column="tutor_id" property="tutorId"/>
  <result column="tutor_name" property="name"/>
  <result column="email" property="email"/>
  <collection property="courses" resultMap="CourseResult"/>
</resultMap>
<select  parameterType="int" resultMap="TutorResult">
  SELECT T.TUTOR_ID,  AS TUTOR_NAME, EMAIL, C.COURSE_ID, , DESCRIPTION, START_DATE, END_DATE
  FROM TUTORS T LEFT OUTER JOIN ADDRESSES A ON T.ADDR_ID=A.ADDR_ID
  LEFT OUTER JOIN COURSES C ON T.TUTOR_ID=C.TUTOR_ID
  WHERE T.TUTOR_ID=#{tutorId}
</select>

Choose This method is suitable for selecting one of the conditions that meets the conditions to generate SQL

<select  parameterType="hashmap" resultMap="CourseResult">
  SELECT * FROM COURSES
  <choose>
    <when test="searchBy == 'Tutor'">
      WHERE TUTOR_ID= #{tutorId}
    </when>
    <when test="searchBy == 'CourseName'">
      WHERE name like #{courseName}
    </when>
    <otherwise>
      WHERE TUTOR start_date  >= now()
    </otherwise>
  </choose>
</select>

where is suitable for selecting all the conditions that satisfy the conditions from multiple conditions to form conditions.

symbol Less than Less than or equal to Greater than Greater than or equal to and Single quotes Double quotes
Original symbol < <= > >= & ' "
Replace symbols &lt; &lt;= &gt; &gt;= &amp; &apos; &quot;
&lt;select  parameterType="hashmap" resultMap="CourseResult"&gt;
  SELECT * FROM COURSES
  &lt;where&gt;  
    &lt;if test=" tutorId != null "&gt;
      TUTOR_ID= #{tutorId}
    &lt;/if&gt;
    &lt;if test="courseName != null"&gt;
      AND name like #{courseName}
    &lt;/if&gt;
    &lt;if test="startDate != null"&gt;
      AND start_date  &gt;= #{startDate} <!--Greater than or equal to Start time-->    &lt;/if&gt;
    &lt;if test="endDate != null"&gt;
      AND end_date  &lt;= #{endDate} <!--less than or equal to end time-->    &lt;/if&gt;
  &lt;/where&gt;
&lt;/select&gt;

foreach

&lt;select  parameterType="" resultType=""&gt;
select * from user
  &lt;where&gt;
    &lt;!--
    collection:Specify the collection properties in the input object.There are three values ​​for this property:list,array,map,Set this value according to the type of the incoming set。
    item:Each traversal of generated objects
    index:The number of current iterations
    open:Splice string when starting traversal
    close:Strings that end up splicing
    separator:Traversing strings that need to be spliced ​​between objects
    select * from user where 1=1 and id in (1,2,3)
    --&gt;
    &lt;foreach collection="list" item="id" open="(" separator="," close=")"&gt;
     #{id}
    &lt;/foreach&gt;
  &lt;/where&gt;
&lt;/select&gt;

select * from user where id=1 or id=2 or id=3

<select  parameterType="" resultType="">
select * from user
  <where>
    <foreach collection="list" item="id" open="and (" close=")" separator="or">
       id=#{id}
    </foreach>
  </where>
</select>

<sql> tag
This tag mainly defines the multiplexed sql statement fragments, and can be directly referenced in the executed sql statement tag. It can improve coding efficiency, simplify code and improve readability.

You need to configure the id to be familiar with, indicating the unique identifier of the sql fragment.

Reference: Reference through the <include ref /> tag, the value of refid is the value of the id attribute of <sql>.

<sql >
  id, question, answer 
</sql>
<select  parameterType="" resultMap="BaseResultMap">
  select 
  <include ref />
  from java
  where id = #{id,jdbcType=BIGINT}
</select>

<set> : It is mainly used to replace the set field in SQL statements, and is generally used in update.

<update>
  update user 
  <set>
    <if test="name != null and ()>0">name = #{name},</if>
    <if test="age != null and age .length()>0">age = #{age },</if>
  </set>
  where id = #{id}
</update>

Batch updates, execute multiple SQLs at once

<update>
    <foreach collection="list" item="item" index="index" separator=";">
        update user 
        <set>
            <if test="name != null and ()>0">name = #{name},</if>
            <if test="age != null and age .length()>0">age = #{age },</if>
        </set>
        <where>
            <if test="id != null and id != ''">
                AND id = #{id,jdbcType=VARCHAR}
            </if>
            <if test="userName != null and userName != ''">
                <bind name="bindUserName" value="'%' + userName + '%'" />
                AND UserName like #{bindUserName}
            </if> 
            <if test="status != null">
                AND Status = #{status,jdbcType=INTEGER}
            </if>
        </where>
    </foreach>
</update>

<trim> : is a formatted tag that can complete the functions of set or where tags.

select * from user 
&lt;trim prefix="WHERE" prefixoverride="AND |OR"&gt;
  &lt;if test="name != null and ()&gt;0"&gt; AND name=#{name}&lt;/if&gt;
  &lt;if test="age != null and ()&gt;0"&gt; AND age=#{age}&lt;/if&gt;
&lt;/trim&gt; 
IfnameandageNone of the values ​​arenullIf it is printedSQLfor:select * from user where name = ‘xx' and age = ‘xx'
existwhereof后面是不存exist第一个andof,上面两个属性of意思如下:
prefix:Prefix
prefixoverride:Remove the first oneandOror
update user
&lt;trim prefix="set" suffixoverride="," suffix=" where id = #{id} "&gt;
  &lt;if test="name != null and ()&gt;0"&gt; name=#{name} , &lt;/if&gt;
  &lt;if test="age!= null and ()&gt;0"&gt; age=#{age} ,  &lt;/if&gt;
&lt;/trim&gt;
IfnameandageNone of the values ​​arenullIf it is printedSQLfor:update user set name=‘xx' , age=‘xx' where id=‘x'
existage='xx'的后面不存exist逗号,And it's automatically addedset前缀andwheresuffix,The above three attributes are as follows,inprefixThe meaning is as above:
 suffixoverride:Remove the last comma(It can also be another mark,It's like the one in the prefix aboveandSame)
   suffix:suffix

choose & foreach list has one value, condition =, multiple values ​​in

<update  parameterType="" >
  update User
  set Status = 1,UpdateTime=(select GETDATE())
  <choose>
    <when test="idList != null and ==1">
      WHERE Id= #{id,jdbcType=VARCHAR}
    </when>
    <when test="idList != null and >1">
      WHERE Id in
      <foreach collection="idList" item="id" open="(" close=")" separator=",">
        <if test="id != null and id != '' ">
          #{id,jdbcType=VARCHAR}
        </if>
      </foreach>
    </when>
    <otherwise>
      WHERE 1=0
    </otherwise>
  </choose>
</update>

This is the end of this article about the summary of MyBatis tag usage. For more related contents of MyBatis tags, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!