动态sql详解
一:where和if标签;
<select id="list" parameterType="AddressBook" resultType="AddressBook">
select * from address_book
<where>
<if test="userId != null">
and user_id = #{userId}
</if>
<if test="phone != null">
and phone = #{phone}
</if>
<if test="isDefault != null">
and is_default = #{isDefault}
</if>
</where>
</select>
1.where标签会动态识别其中语句中的and,or关键字并且自动去除条件起前面多余的and和or,如果where内部的if都不成立,甚至连where自身都不会拼接;
2.if标签用于判断,成立则拼接内部语句,否之则不拼接;
二:foreach标签;
<select id="getSetmealIdsByDishIds" resultType="java.lang.Long">
select setmeal_id from setmeal_dish where dish_id in
<foreach collection="dishIds" item="dishId" separator="," open="(" close=")">
#{dishId}
</foreach>
</select>
1.foreach collection表示集合的名字,item表示集合的元素,separator表示分隔符,open,close表示开头和结尾的符号;
2.形成的sql语句就类似于 select setmeal_id from setmeal_dish where dish_id in (1,2,3);
三:set标签;
<update id="update">
update orders
<set>
<if test="status != null">
status = #{status},
</if>
<if test="payStatus != null">
pay_status = #{payStatus},
</if>
<if test="deliveryStatus != null">
delivery_status = #{deliveryStatus},
</if>
<if test="cancelReason != null">
cancel_reason = #{cancelReason},
</if>
<if test="cancelTime != null">
cancel_time = #{cancelTime},
</if>
</set>
</update>
1.用于替代update语句中的set关键字,并且能动态去除多余的, ;
四:sql include标签:
略.....;
本博客所有文章除特别声明外,均采用 CC BY-NC-SA 4.0 许可协议。转载请注明来源 Hexo!

