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
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 = SqlSessionUtil.getMapper(EmployeeMapper.class, true);
boolean flag = employeeMapper.delete(9L);
Assert.assertEquals(true, flag);
}
// 测试批量删除
@Test
public void batchDelete(){
EmployeeMapper employeeMapper = SqlSessionUtil.getMapper(EmployeeMapper.class, true);
List<Long> idList = Arrays.asList(1L, 2L, 3L, 4L, 5L);
long cnt = employeeMapper.batchDelete(idList);
Assert.assertEquals(5L, cnt);
标签:14,删除,employeeMapper,sql,Mybatis,EmployeeMapper,id,delete 来源: https://blog.csdn.net/u011250186/article/details/118875906