14.Mybatis删除操作-delete
1. delete 标签
delete 标签是⽤于定义delete 语句的.
1.1 常⽤属性
delete 有⼏个常⽤的属性, 但是通常只需要设置id 即可.
id: sql ⽚段在命名空间内的唯⼀标识. 和mapper 中⽅法名保持⼀致
parameterType: 参数类型, 通常都可以省略.
flushCache: 是否刷新(清空)⼀级缓存和⼆级缓存, 默认为true. 笔者尝试设置为false,并不⽣效. 所以使⽤默认即可.
timeout: sql 执⾏超时时间, 默认未设置, 由数据库驱动决定.
statementType: 执⾏sql时使⽤的statement类型, 默认为PREPARED. 可选值为:STATEMENT,PREPARED 或 CALLABLE 的⼀个
<delete id="deleteAuthor" parameterType="domain.blog.Author" flushCache="true" statementType="PREPARED"
timeout="20">
</delete>
1.2 返回值
我们知道, jdbc 执⾏删除语句时, 返回的是sql 执⾏影响的记录条数. Mybatis 可将此返回结果⾃动封装为int , long, boolean 以及其对应的包装类型.
对于不同的返回类型, sql ⽚段的写法是完全⼀致的
Mapper中⽅法定义:
// 返回值为空
void delete(Long id);
// 返回值为布尔类型
boolean delete(Long id);
// 返回值为删除的条数
long delete(Long id);
sql ⽚段:
<delete id="delete">
delete from t_employee where id = #{id}
</delete>
2. delete 标签举例
2.1 sql ⽚段
<!-- 通过id 删除 -->
<delete id="delete">
delete from t_employee where id = #{id}
</delete>
<!-- 批量删除 -->
<delete id="batchDelete">
delete from t_employee
sql中delete用法where id in
<foreach collection="list" open="(" separator="," close=")" item="id">
#{id}
</foreach>
</delete>
2.2 mapper ⽂件
public interface EmployeeMapper {
// 删除, 返回是否删除
boolean delete(Long id);
// 批量删除, 返回成功删除的个数
long batchDelete(List<Long> ids);
}
2.3 测试类
// 测试删除⽅法
@Test
public void delete(){
EmployeeMapper employeeMapper = Mapper(EmployeeMapper.class, true); boolean flag = employeeMapper.delete(9L);
Assert.assertEquals(true, flag);
}
// 测试批量删除
@Test
public void batchDelete(){
EmployeeMapper employeeMapper = Mapper(EmployeeMapper.class, true);
List<Long> idList = Arrays.asList(1L, 2L, 3L, 4L, 5L);
long cnt = employeeMapper.batchDelete(idList);
Assert.assertEquals(5L, cnt);
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。
发表评论