Common tags and usage of MyBaties dynamic SQL

The elements used to implement dynamic SQL in MyBatis mainly include:

  1. if
  2. choose(when,otherwise)
  3. trim
  4. where
  5. set
  6. foreach

(1).if tag: conditional judgment

<select id="findActiveBlogLike" resultType="Blog">
  SELECT * FROM BLOG WHERE state = "ACTIVE"
  <if test="title != null">
    AND title like #{title}
  </if>
  <if test="author != null and author.name != null">
    AND author_name like #{author.name}
  </if>
</select>

(2).choose, when, otherwise tags: complex condition judgment

Mybatis does not have if...else. In the sql mapper file of mybatis, choose...when...otherwise is used for conditional judgment.

The choose tag judges in order whether the test conditions in the internal when tag are true, and if one is true, the choose ends. When all the conditions of when 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.

<select id="findActiveBlogLike" resultType="Blog">
  SELECT * FROM BLOG WHERE state = "ACTIVE"
  <choose>
    <when test="title != null">
      AND title like #{title}
    </when>
    <when test="author != null and author.name != null">
      AND author_name like #{author.name}
    </when>
    <otherwise>
      AND featured = 1
    </otherwise>
  </choose>
</select>

(3).trim, where, set tags

<select id="findActiveBlogLike" resultType="Blog">
  SELECT * FROM BLOG
  <where>
    <if test="state != null">
         state = #{state}
    </if>
    <if test="title != null">
        AND title like #{title}
    </if>
    <if test="author != null and author.name != null">
        AND author_name like #{author.name}
    </if>
  </where>
</select>

The where element will only insert a "WHERE" clause if there is at least one child element whose condition returns an SQL clause. Also, if the statement starts with "AND" or "OR", the where element will strip them out as well.

(4).foreach tag: traverse collection elements

Another common operation requirement of dynamic SQL is to traverse a collection, usually when building IN conditional statements. for example:

<select id="selectPostIn" resultType="domain.blog.Post">
  SELECT *
  FROM POST P
  WHERE ID in
  <foreach item="item" index="index" collection="list"
      open="(" separator="," close=")">
        #{item}
  </foreach>
</select>

The function of the oreach element is very powerful, it allows you to specify a collection, and declares collection item (item) and index (index) variables that can be used in the element body. It also allows you to specify start and end strings and place separators between iteration results. This element is smart so it doesn't accidentally append extra separators.

Guess you like

Origin blog.csdn.net/qq_45349018/article/details/104852057