2024/11/3日工作总结
学习mybatis操作数据库删除以及批量删除功能
点击查看代码
<delete id="deleteById">
delete from tb_brand where id = #{id}
</delete>
<!--
mybatis会将数组参数封装为一个map集合
*默认:array = 数组
*@Param改变map集合的默认key名称
-->
<delete id="deleteByIds">
delete from tb_brand where id
in(
<foreach collection="ids" item="id" separator="," open="(" close=")">
#{id}
</foreach>
)
</delete>
点击查看代码
@Test
public void testDeleteById() throws IOException {
int id = 7;
//1.获取SqlSessionFactory
String resource = "mybatis-config.xml";
InputStream inputStream = Resources.getResourceAsStream(resource);
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
//2.获取SqlSession对象,true设置自动提交事务
SqlSession sqlSession = sqlSessionFactory.openSession(true);
//3.获取Mapper接口代理对象
BrandMapper brandMapper = sqlSession.getMapper(BrandMapper.class);
//4.执行方法
brandMapper.deleteById(id);
//提交事务
/*sqlSession.commit();*/
//5.释放
sqlSession.close();
}
@Test
public void testDeleteByIds() throws IOException {
int[] ids = {5,6};
//1.获取SqlSessionFactory
String resource = "mybatis-config.xml";
InputStream inputStream = Resources.getResourceAsStream(resource);
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
//2.获取SqlSession对象,true设置自动提交事务
SqlSession sqlSession = sqlSessionFactory.openSession(true);
//3.获取Mapper接口代理对象
BrandMapper brandMapper = sqlSession.getMapper(BrandMapper.class);
//4.执行方法
brandMapper.deleteByIds(ids);
//提交事务
/*sqlSession.commit();*/
//5.释放
sqlSession.close();
}

浙公网安备 33010602011771号