1. 動態 SQL 之<if>標籤
* 注意:<if>標籤的 test 屬性中寫的是對象的屬性名.
* 如果是包裝類的對象要使用 OGNL 表達式的寫法。
* 另外要注意 where 1=1 的作用~!
* 例如:
<select id="findAll" resultType="com.yang.daomain.User">
select * from user where 1= 1
<if test="and username != null ">
username = #{username}
</if>
</select>
2. 動態 SQL 之<where>標籤
* 爲了簡化上面 where 1=1 的條件拼裝.
* 我們可以採用<where>標籤來簡化開發。
* 例如:
<select id="findAll" resultType="com.yang.daomain.User">
select * from user
<where>
<if test="and username != null">
username = #{username}
</if>
<if test="userSex != null ">
and sex = #{userSex}
</if>
</where>
</select>
3. 動態標籤之<foreach>標籤
* SQL 語句: select 字段 from user where id in (?)
* <foreach>標籤用於遍歷集合,它的屬性:
* collection:代表要遍歷的集合元素,注意編寫時不要寫#{}
* open:代表語句的開始部分
* close:代表結束部分
* item:代表遍歷集合的每個元素,生成的變量名
* sperator:代表分隔符
* 例如:
<select id="findUserInIds" resultMap="userMap" parameterType="queryVo">
<include refid="defaultUser"/>
<where>
<if test="ids != null and ids.size() > 0">
<foreach collection="ids" open="and id in("close =")" item="uid" separator=",">
#{uid}
</foreach>
</if>
</where>
</select>
4. 引用代碼片段
<sql id="defaultUser"> id是別的sql引用時需要名字
select * from user
</sql>
此時的查詢:
<select id="findAll" resultMap="userMap">
<include refid="defaultUser"/>
</select>