mybatis動態sql使用的標籤:java
1:if 判斷sql
2:where 解決sql語句拼接條件問題數組
例:
mybatis
<select id="findUserById" resultType="user">dom
select * from user where spa
<where>
code
<if test="id != null">orm
id=#{id}it
</if>io
and deleteFlag=0;
</where>
</select>
若是id = null 則sql語句會爲: select * from user where and and deleteFlag=0,很明顯這個是錯誤的sql語句。添加where便籤變能夠解決,如上<where></where> 去掉上面紅色部分where
3:trim 處理拼接
2中的問題也能夠這樣處理
<select id="findUserById" resultType="user">
<trim prefix="where" prefixOverrodes="and | or">
select * from user where
<if test="id != null">
id=#{id}
</if>
and deleteFlag=0;
</trim>
</select>
4: set
<update id="updateUser" parameterType="com.domin.User">
update user set
<set>
<if test="name != null">
name = #{name},
</if>
</set>
and deleteFlag = 0;
</where>
</update>
若是name = null,則sql語句爲update user set and deleteFlag = 0,明顯錯誤。使用<set></set> 替代<set>
也能夠是trim處理
5:foreach 循環遍歷集合或數組
<select id="selectUser" resultType="domain.domin.User">
select *
from user
where id in
<foreach item="item" index="index" collection="list"
open="(" separator="," close=")">
#{item}
</foreach>
</select>
對應的sql以下:
select * from user where id in(item1,item2...)
item1,item2...表明#{item}每次的值
6:choose 至關於java中的swich
格式以下:
<choose>
<when>
語句
</when>
<otherwise>
語句
</otherwise>
</choose>
遇到的問題:
<![CDATA[ AND shelve_at <= #{currentTimeMillis,jdbcType=BIGINT} AND #{currentTimeMillis,jdbcType=BIGINT} < unshelve_at ]]> //不能寫成 <![CDATA[ AND shelve_at <= #{currentTimeMillis,jdbcType=BIGINT} < unshelve_at ]]>