這裏提到的動態SQL用法都是基於mapper的xml配置文件的。java
一、if 這個標籤能夠用於多條件查詢,也能夠用於新增/更新數據時的空值判斷。sql
<select id="selectUser" resultType="com.forest.owl.entity.User"> select * from user where 1=1 <if test="userName != null and userName != '' "> and user_name like concat('%', #{userName}, '%') </if> <if test="userPhone != null and userPhone !='' "> and user_phone=#{userPhone} </if> </select>
二、choose,用於模式匹配數組
<select id="selectUser" resultType="com.forest.owl.entity.User"> select * from user where 1=1 /*此處不可忽略*/ <choose> <when test="id != null"> and id=#{id} </when> <when test="userName != null and userName !='' "> and user_name=#{userName} </when> <otherwise> and 1=2 /*此處不可忽略*/ </otherwise> </choose> </select>
三、where,結合if使用app
where標籤內若是沒有符合條件的選項,則最後生成的sql語句不含where;若是有符合條件的,則生成的sql語句會自動去除兩端的and測試
<select id="selectUser" resultType="com.forest.owl.entity.User"> select * from user <where> <if test="userName != null and userName != '' "> and user_name like concat('%', #{userName}, '%') </if> <if test="userEmail != null and userEmail != '' "> and user_email = #{userEmail} </if> </where> </select>
四、set,結合if使用rest
<update id="updateUserById"> update user <set> <if test="userName != null and userName != '' "> user_name=#{userName}, </if> id=#{id} /*此處不可忽略*/ </set> where id=#{id} </update>
五、foreachcode
collection:必填,值爲要迭代循環的屬性名。xml
item:變量名,值爲要從迭代對象中取出的每個值對象
index:索引的屬性名。在集合數組下爲索引值,在Map對象下爲Map的key值。索引
參數爲List的狀況
<select id="selectByIdList" resultType="com.forest.owl.entity.User"> select * from user where id in <foreach collection="list" open="(" close=")" separator="," item="id" index="i"> #{id} </foreach> </select>
參數爲Map的狀況
<update id="updateByMap"> update user set <foreach collection="_parameter" item="val" index="key" separator=","> ${key}=#{val} </foreach> where id=#{id} </update>
六、bind
bind標籤可使用OGML表達式建立一個變量並綁定到上下文中。如:
<if test="userName != null and userName != '' "> and user_name like concat('%', #{userName}, '%') </if>
能夠經過bind改寫成
<if test="userName != null and userName != '' "> <bind name="userNameLike" value=" '%' + userName + '%' "/> and user_name #{userNameLike} </if>
七、若是測試的時候想知道映射XML中方法執行的參數 能夠這麼作:
public class StringUtil{ public static void print(Object parameter){ System.out.println(parameter); } }
<bind name="print" value="@com.forest.owl.util.StringUtil@print(_parameter)" />
八、鑑別器映射(discriminator) 有時單獨一個映射會須要返回不一樣數據類型的結果集,discriminator就是爲了用來處理這種狀況。
由於感受這個標籤不會很經常使用,因此不作進一步瞭解,暫時給出簡單的代碼,後續有須要再回來翻閱:
<resultMap id="UserAndRole" extends="BaseResultMap" type="com.forest.owl.entity.User"> <discriminator javaType="int" column="enabled"> <case value="1" resultMap="resultMap1"/> <case value="2" resultMap="resultMap2"/> </discriminator> </resultMap>
九、既然提到了動態sql,就額外提一下在註解形式下怎麼寫mapper吧。由於當前作的項目用到了這種方式,就在此mark一下。 舉個多條件查詢的小例子):
@Select("<script> select id, name from user <where> <if test='user.id != null'>id = #{user.id}</if> <if test='user.name != null'>name like concat('%',#{user.name},'%')</if> </where> </script>") User selectUser(@Param("user") User user);