Dynamic SQL splicing in MyBatis

if tag

The if tag is usually used in WHERE statements, UPDATE statements, and INSERT statements. It determines whether to use a certain query condition, whether to update a certain field, and whether to insert the value of a certain field by judging the parameter value.

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

foreach tag

The foreach tag is mainly used to construct in conditions, which can iterate over the collection in sql. It is also commonly used in operations such as batch deletion and addition.

<!-- in查询所有,不分页 -->
<select id="selectIn" resultMap="BaseResultMap">
    select name,hobby from student where id in
    <foreach item="item" index="index" collection="list" open="(" separator="," close=")">
        #{item}
    </foreach>
</select>
1234567

Property introduction:

  • collection: There are three values ​​for the collection attribute: list, array, and map, and the corresponding parameter types are: List, array, and map collection.
  • item: represents the alias of each element in the iteration process
  • index: indicates the position (subscript) reached during each iteration in the iteration process
  • open: prefix
  • close: suffix
  • separator: Separator, indicating what separation between each element during iteration

choose tag

Sometimes we don't want to apply all the conditions, but just want to choose one from multiple options. MyBatis provides the choose element to determine whether the conditions in when are established in order. If one is established, choose ends. When all the when
conditions in choose are not satisfied, the sql in otherwise is executed. Similar to the switch statement in Java, choose is switch, when is case, and otherwise is default.

if is the relationship with (and), and choose is the relationship with (or).

<select id="getStudentListChoose" parameterType="Student" resultMap="BaseResultMap">
    SELECT * from STUDENT
    <where>
        <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>
    </where>
</select>

Guess you like

Origin blog.csdn.net/WziH_CSDN/article/details/108804522