mybatis dynamic sql

MYBATIS Dynamic SQL

Dynamic SQL is a very powerful feature of MyBatis. It enables to build queries based on the scenario dynamically.

1
2
3
4
5
6
7
8
9
10
11
<select id = "getRecByName_Id" parameterType = "Student" resultType = "Student">
SELECT * FROM STUDENT
<if test = "name != null">
WHERE name LIKE #{name}
</if>
<if test = "id != null">
AND id LIKE #{id}
</if>
</select>

The choose, when, and otherwise Statements

a choose element, which is similar to Java’s switch statement.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
<select id = "getName_Id_phone" parameterType = "Student" resultType = "Student">
SELECT * FROM STUDENT
<where>
<if test = "id != null">
id = #{id}
</if>
<if test = "name != null">
AND name LIKE #{name}
</if>
</where>
</select>

The foreach Statement

foreach element allows you to specify a collection and declare item and index variables that can be used inside the body of the element

1
2
3
4
5
6
7
8
9
10
11
<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>