1 什么是動(dòng)態(tài) sql
mybatis 對(duì) sql 語句進(jìn)行靈活操作,通過表達(dá)式進(jìn)行判斷,從而對(duì)sql進(jìn)行靈活的封裝。
2 if 的用法
需求:從學(xué)生表(students)中查詢用戶信息,對(duì)查詢條件進(jìn)行判斷,如果不為空,則進(jìn)行條件拼接。
mapper.xml
<mapper namespace="_4dynamicSql.StudentMapper">
<select id="findStudents" resultType="_4dynamicSql.Student"
parameterType="_4dynamicSql.StudentVo">
SELECT id,name,sal FROM students
<!--
使用where可以自動(dòng)省掉sql中的第一個(gè)and
-->
<where>
<if test="studentCustom!=null">
<if test=" studentCustom.name != null
and studentCustom.name != ''">
AND name = #{studentCustom.name}
</if>
<if test="studentCustom.sal != null and
studentCustom.sal != ''">
AND sal = #{studentCustom.sal}
</if>
</if>
</where>
</select>
</mapper>
3 sql片段引用
mybatis.xml
<!--
定義 sql 片段
id:sql片段唯一標(biāo)示符
-->
<sql id="query_student_where" >
<if test="studentCustom!=null">
<if test=" studentCustom.name != null and
studentCustom.name != ''">
and name = #{studentCustom.name}
</if>
<if test="studentCustom.sal != null and
studentCustom.sal != ''">
AND sal = #{studentCustom.sal}
</if>
</if>
</sql>
<select id="findStudents" resultType="_4dynamicSql.Student"
parameterType="_4dynamicSql.StudentVo">
SELECT id,name,sal FROM students
<where>
<include refid="query_student_where"/>
</where>
</select>
3 foreach
實(shí)現(xiàn)該sql語句的拼接
AND (id=1 OR id=2 OR id=4)
<!--
使用 foreach 遍歷傳入data
collection:指定輸入對(duì)象中集合屬性
item:每次遍歷的項(xiàng)
open:開始遍歷時(shí)拼接的串
close:結(jié)束時(shí)遍歷拼接的串
separator:遍歷的兩個(gè)對(duì)象之間的串
-->
<foreach collection="data" item="item" open=" AND (" close=")"
separator="OR">
id=#{item}
</foreach>