动态SQL
(1)NoteDao接口中定义方法
public int updateNoteByMap(Map<String, Object>map);
(2)
Mapper.xml文件配置
<update id="updateNoteByMap" parameterType="Map">
update cn_note
set
<trim suffixOverrides=",">
<if test="title!=null">
cn_note_title=#{title},
</if>
<if test="body!=null">
cn_note_body=#{body},
</if>
<choose>
<when test="time!=null">
cn_note_last_modify_time=#{time}
</when>
<otherwise>
cn_note_last_modify_time=unix_timestamp()
</otherwise>
</choose>
</trim>
where
cn_note_id=#{noteId}
</update>
批量删除
(1)NoteDao接口类添加
/*
* map中需要添加两个参数
* ids代表被删除笔记的id列表
* status代表被删除笔记的 状态属性
* map={ids:[id1,id2,id3...],status:2}
*/
public int deleteNotes(Map<String,Object>map);
(2)配置mapper.xml文件
<delete id="deleteNotes"
parameterType="map">
delete from cn_note
where
<if test="status!=null">
cn_note_status_id=#{status} and
cn_note_id in
<foreach collection="ids"
item="id"
open="("
separator=","
close=")">
#{id}
</foreach>
</if>
</delete>
Junit测试:
private NoteDao noteDao;
@Before
public void init(){
noteDao=super.getContext().getBean("noteDao",NoteDao.class);
}
@Test
public void testDeleteNotes(){
Map<String,Object> map= new HashMap<String, Object>();
String[] ids={"019cd9e1-b629-4d8d-afd7-2aa9e2d6afe0","id2","id3"};
map.put("ids",ids);
map.put("status", 1);
int n =noteDao.deleteNotes(map);
System.out.println(n);
}
编程事物处理
try{
开启事物
处理事物过程
CRUD...
提交事物
}catch(Exception e){
出现异常:回顾
}finally{
释放资源
}
AOP:声明式事物处理
try{
@Before
@Transactional
处理事物过程
CRUD...
@AfterReturning
}catch(Exception e){
@AfterThrowing
出现异常:回顾
}finally{
@After
}
(1)NoteDao接口定义方法
int deleteNote(Stringid);
(2)NoteService接口定义方法
//String ...动态参数 就是String[]数组
void deleteNotes(String ...ids);
(3)NoteServiceImpl实现类重写NoteService中方法
@Transactional
public void deleteNotes(String...ids) {
for (String id : ids) {
int n=noteDao.deleteNote(id);
if(n!=1){
//抛出异常触发,事物的回滚
throw new RuntimeException("删错了");
}
}
调用动态参数的时候,可以不创建参数,直接写参数
形如:
noteService.deleteNotes(“id1”,”id2”,”id3”);
