How to understand the dynamic and static of sql in mybatis

In MyBatis, SQL statements can be divided into dynamic and static. Static SQL refers to the SQL statement that has been fixed when the application program writes the SQL statement, while dynamic SQL refers to the SQL statement that can be dynamically generated according to the conditions.

Dynamic SQL is very common in actual development. It can combine if, choose, when, otherwise, foreach and other elements according to conditions to generate different SQL statements.

The following are some common dynamic SQL:

if element: The if element is a conditional judgment, which can determine whether to include SQL statement fragments according to the condition. Sample code:

<select id="selectBlog" resultType="Blog">
  select * from Blog
  <where>
    <if test="title != null">
      and title like #{title}
    </if>
    <if test="author != null">
      and author like #{author}
    </if>
  </where>
</select>

choose element: The choose element is similar to the switch statement in Java, which can match the when element according to the condition, and execute the otherwise element if none of them match. Sample code:

<select id="selectBlog" resultType="Blog">
  select * from Blog
  <where>
    <choose>
      <when test="title != null">
        and title like #{title}
      </when>
      <when test="author != null">
        and author like #{author}
      </when>
      <otherwise>
        and 1=1
      </otherwise>
    </choose>
  </where>
</select>

foreach element: The foreach element can be used to iterate a collection or array and pass the elements in the collection or array as SQL parameters. Sample code:

<select id="selectBlog" resultType="Blog">
  select * from Blog where id in
  <foreach item="item" index="index" collection="ids" open="(" separator="," close=")">
    #{item}
  </foreach>
</select>

Through dynamic SQL, the writing of SQL can be greatly simplified, and a more flexible combination of SQL statements can be realized.

2023 version of MyBatis tutorial zero-based crash course (core explanation, comprehensive mastery)

Guess you like

Origin blog.csdn.net/GUDUzhongliang/article/details/131557142