動態SQL
在使用JDBC拼接SQL的時候,經常要確保不能完了必要的空格,對于的逗號,而mybatis的動態SQL則完美的解決了這些問題。本文只介紹利用mybatis的動態SQL解決常見的SQL拼接問題。
mybatis的動態sql包含一下內容:
- if
- choose,when,otherwise
- trim,where,set
- foreach
- bind
解決where后SQL條件判斷問題
<select id="selectByParam" parameterType="int" resultMap="studentResult">
select * from student where
<if test="studentId != null">
student_id = #{studentId}
</if>
<if test="studentAge != null">
and student_age = #{studentAge}
</if>
<if test="studentPhone != null">
and student_phone = #{studentPhone}
</if>
</select>
在上名的sql中,如果三個if條件全為空,則最后拼接的sql為:
select * from student where
如果第一個為判斷為空,則最后拼接的sql為:
select * from student where and student_age = #{studentAge} and student_phone = #{studentPhone}
上面拼接的兩個sql語法都存在問題,只需要利用一點小技巧就能解決這個問題。如下,利用<where></where>標簽,mybatis會自動處理上面的問題。
<select id="selectByParam" parameterType="int" resultMap="studentResult">
select * from student
<where>
<if test="studentId != null">
student_id = #{studentId}
</if>
<if test="studentAge != null">
and student_age = #{studentAge}
</if>
<if test="studentPhone != null">
and student_phone = #{studentPhone}
</if>
</where>
</select>
也可以利用trim來解決
<select id="selectByParam" parameterType="int" resultMap="studentResult">
select * from student
<trim prefix="WHERE" prefixOverrides="AND |OR ">
<if test="studentId != null">
student_id = #{studentId}
</if>
<if test="studentAge != null">
and student_age = #{studentAge}
</if>
<if test="studentPhone != null">
and student_phone = #{studentPhone}
</if>
</trim>
</select>
利用<set>或<trim>解決update中set逗號問題
<update id = "updateById">
update student
<if test="studentName != null">student_name = #{studentName},</if>
<if test="studentAge != null">student_age = #{studentAge},</if>
<if test="studentPhone != null">student_name = student_phone = #{studentPhone},</if>
where student_id = #{studentId}
</update>
從上面可以看出,set始終會多一個逗號。解決方案如下:
<update id = "updateById">
update student
<set>
<if test="studentName != null">student_name = #{studentName},</if>
<if test="studentAge != null">student_age = #{studentAge},</if>
<if test="studentPhone != null">student_name = student_phone = #{studentPhone},</if>
</set>
where student_id = #{studentId}
</update>
或者
<update id = "updateById">
update student
<trim prefix="SET" suffixOverrides=",">
<if test="studentName != null">student_name = #{studentName},</if>
<if test="studentAge != null">student_age = #{studentAge},</if>
<if test="studentPhone != null">student_name = student_phone = #{studentPhone},</if>
</trim>
where student_id = #{studentId}
</update>
利用foreach查詢
<select id="selectByIds" parameterType="int" resultMap="studentResult">
select
<include refid="studentSql"/>
from student where student_id in
<foreach collection="list" item="item" index="index" open="(" separator="," close=")">
#{item}
</foreach>
</select>