第三章动态SQL
-----if標簽:
用法類似Java中的if語句,選擇性拼接指定SQL片段.
代碼示例:
<!--測試if標簽: age條件--> <select id="dynacSQL1" resultType="user" parameterType="user" >select * from user<if test="age!=0">where age=#{age}</if> </select>-----choose,when,otherwise標簽
用法類似Java的if else if 語句,用于多次判斷,選擇性拼接指定SQL片段.
代碼實例:
<!--測試choose>,<when>,<otherwise>標簽: age為多少歲--> <select id="dynacSQL2" resultType="user" parameterType="user" >select * from user<choose><when test="age==0">where age>0</when><when test="age!=0">where age=#{age}</when></choose> </select>-----forEach標簽:
用于遍歷集合,通常用于構建in語句中.
代碼實例
<!--測試<forEach: 測試age為20,21,22,23,24,25--><select id="dynacSQL3" resultType="user" parameterType="java.util.ArrayList" >select * from user where age in<foreach collection="array" item="ageval" open="(" separator="," close=")">#{ageval}</foreach> </select>-----where標簽:
要求:<where>需要與<if>,<choose>,<when>,<otherwise>等配合使用 作用:a.當至少有1個子標簽的條件為true時,<where>生成1個"where"關鍵字.b.若where后緊挨"AND/OR"時[where and 條件],<where>自動去除. 格式:<where>其他動態SQL標簽</where>說明:1.<where>標簽中編寫<if>,<choose>,<when>,<otherwise>,<forEach>等標簽代碼實例
<!--測試<where>: 測試age為20,21,22--> <select id="dynacSQL4" resultType="user" parameterType="user" >select * from user<where><if test="age==20">age=20</if><if test="age==21">age=21</if><if test="age==22">age=22</if></where> </select>-----set標簽:
用于修改命令中,能夠動態前置"set"關鍵字,同時可以刪除多余的逗號.
代碼實例
<!--測試set標簽: 修改用戶信息--> <update id="dynacSQL5" parameterType="user" >update user<set><if test="name!=null">name=#{name},</if><if test="sex!=null">sex=#{sex},</if><if test="age!=0">age=#{age},</if><if test="address!=null">address=#{address}</if></set>where id=#{id} </update>-----sql標簽
在業務標簽外,定義一個SQL片段,在其他業務標簽中可以通過引用該SQL片段.
代碼實例
<!--測試sql標簽: 字段--> <sql id="tableConum" >id,name,sex,age,address </sql> <select id="dynacSQL6" resultType="user" >select <include refid="tableConum" /> from user </select>總結
- 上一篇: 第二章mapper接口 和模糊查询
- 下一篇: 第四章关联映射