MyBatis中的动态SQL主要通过以下方式实现:
- if:
<select id="findByAge" parameterType="int" resultType="hashmap">
select * from user
<if test="age != null">
where age = #{age}
</if>
</select>
根据参数age是否不为null,决定是否生成where子句。
- choose, when:
<select id="findByCondition" parameterType="map" resultType="hashmap">
select * from user
<choose>
<when test="sex != null">
and sex = #{sex}
</when>
<when test="age != null">
and age = #{age}
</when>
</choose>
</select>
传入的条件构建动态where语句。
- foreach:
<select id="selectPostIn" resultType="map">
select * from post
where id in
<foreach item="item" index="index" collection="list"
open="(" separator="," close=")">
#{item}
</foreach>
</select>
迭代集合,生成in子句中的多个逗号分隔的值。
- trim:
<select id="trial" resultType="hashmap">
SELECT * FROM USER
<where>
<if test="username != null">
username = #{username}
</if>
<if test="sex != null">
AND sex = #{sex}
</if>
</where>
</select>
trim用于去除where语句前面的and/or。
- sql片段:
<sql id="if-sex">
<if test="sex != null" >
and sex = #{sex}
</if>
</sql>
<include refid="if-sex"/>
定义可重用的SQL片段,使用引用。