多选删除,修改笔记的类型,会出现性能差,用一个sql最好。
MyBatis提供的动态SQL拼接功能,可以优化数据层操作,减少冗余SQL的产生,进而提供数据访问性能。
动态SQL经常与数组,List,Map 参数配合使用。
动态update
update
cn_note
set
cn_note_type_id='2'
where
cn_note_id in
<foreach collection="array" item="id" open="("
separator="," close=")">
#{id}
</foreach>
以上代码中:
- 数组参数时候
<update>
元素无需使用属性parameterType <foreach>
元素是迭代元素
- collection=”array”表示方法接收参数是数组
- item=”id”用于声明迭代期间的变量名与
#{id}对应
-open=”(” separator=”,” close=”)”用于声明迭代结果的开始符号,分隔符和结束符号
index=”idx”用于声明迭代序号变量
map作为参数
<update id="updateNotes"
parameterType="map">
update
cn_note
<set>
//判断语句,如果typeId不为空,
//则执行下面的语句
<if test="typeId!=null">
cn_note_type_id=#{type},
</if>
<if test="title!=null">
cn_note_title=#{title},
</if>
<if test="lastModifyTime!=null">
cn_note_last_modify_time=#{lastModifyTime}
</if>
</set>
where
cn_note_id in
<foreach collection="ids" item="id"
open="(" separator="," close=")">
#{id}
</foreach>
</update>
-
数组参数时候<update>元素无需使用属性 paramaterType
<foreach> 元素是迭代元素
collection="list" 表示方法接收参数是List集合
多项选择
<choose>
<when test="lastModifyTime!=null">
cn_note_last_nodify_time=#{lastModifyTime}
</when>
<when test="modifyBegin!=null and modifyEnd!=null>
cn_note_last_modify_time between
#{modifyBegin} and #{modifyEnd} and
</when>
<when test="modifyBegin!=null">
cn_note_last_modify_time >
#{modifyBegin}
</when>
<when test="modifyEnd!=null">
cn_note_last_modify_time <
#{modifyEnd}
</when>
</choose>
<if test="ids!=null">
cn_note_id in
<foreach collection="ids"
item="id"
open="(" separator="," close=")">#{id}
</foreach>
</where>
</chooose>
提示:
- 用于消除两端多余的and/or
<choose>
用于实现多路分支
2.实现删除业务层方法
创建业务层接口方法NotebookService.java;
/**
*批量删除方法,批量删除
*指定的笔记
*/
void deleteNotes(String… ids);
实现方法NotebookServiceImpl.java
@Transactional
public void deleteNotes(String… ids){
//检验被更新的数据是否存在
//拼凑查询条件
Map