MyBatis实现删除操作
文章目录
1 删除一个
接口
/**
* 根据id删除
*/
void deleteById(int id);
SQL映射
<!--根据id删除-->
<delete id="deleteById">
delete
from tb_brand
where id = #{id};
</delete>
测试
删除前
@Test
public void testDeleteById() throws IOException {
// 设置参数
int id = 6;
// 1.获取SQLSessionFactory
String resource = "mybatis-config.xml";
InputStream inputStream = Resources.getResourceAsStream(resource);
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
// 2. 获取SqlSession对象
// 设置为自动提交事务
SqlSession sqlSession = sqlSessionFactory.openSession(true);
// 3. 获取Mapper接口的代理对象
BrandMapper brandMapper = sqlSession.getMapper(BrandMapper.class);
// 4. 执行方法
brandMapper.deleteById(id);
// 5. 释放资源
sqlSession.close();
}
删除后
2 批量删除
最初的sql配置为
<delete id="deleteByIds">
delete
from tb_brand
where id in (?,?,?);
</delete>
这样存在问题是不能动态的删除
问号为占位符,但是不知道要删除几个,所以占位符不知道要放多少个
解决办法:
使用标签
注意:
MyBatis会将数组参数,封装为一个Map集合。
- 默认:array = 数组
- 使用 @Param注解改变map集合的默认key的名称
本次使用@Param注解的方式
接口
/**
* 批量删除
*/
void deleteByIds(@Param("ids") int[] ids);
sql映射
<!-- 批量删除-->
<delete id="deleteByIds">
delete
from tb_brand
where id
in (
<foreach collection="ids" item="id" separator=",">
#{id}
</foreach>
);
</delete>
测试
删除 7 8 9
@Test
public void testDeleteByIds() throws IOException {
// 设置参数
int[] ids = {
7, 8, 9};
// 1.获取SQLSessionFactory
String resource = "mybatis-config.xml";
InputStream inputStream = Resources.getResourceAsStream(resource);
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
// 2. 获取SqlSession对象
// 设置为自动提交事务
SqlSession sqlSession = sqlSessionFactory.openSession(true);
// 3. 获取Mapper接口的代理对象
BrandMapper brandMapper = sqlSession.getMapper(BrandMapper.class);
// 4. 执行方法
brandMapper.deleteByIds(ids);
// 5. 释放资源
sqlSession.close();
}
优化
优化sql映射配置文件
使用属性open和close 这样可以省略在外面手动添加括号,由MyBatis自动添加
<delete id="deleteByIds">
delete
from tb_brand
where id
in
<foreach collection="ids" item="id" separator="," open="(" close=")">
#{id}
</foreach>
;
</delete>