删除&批量删除功能 && foreach
1.编写接口方法:Mapper
参数:id
结果:void
2.编写SQL语句:SQL映射文件
3.执行方法,测试
步骤一:
步骤二:
步骤三:
//删除数据 public void testAdd() throws IOException { //接受参数 //现在是固定数据,以后会变成动态数据 int id = 1; //处理参数,定义一个关键字,将查询的关键字封装 Brand brand = new Brand(); brand.setId(id); //1. 获取SqlSessionFactory String resource = "mybatis-config.xml"; InputStream inputStream = Resources.getResourceAsStream(resource); SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream); //2.获取Sqlsession对象 //SqlSession sqlSession = sqlSessionFactory.openSession(); SqlSession sqlSession = sqlSessionFactory.openSession(true); //3.获取Mapper接口的代理对象 BrandMapper brandMapper = sqlSession.getMapper(BrandMapper.class); //4.执行方法 brandMapper.deleteById(brand.getId()); //5.释放资源 sqlSession.close(); }
批量删除
步骤一 @param修改数组参数值
步骤二
步骤三:调用和传入ids数组
public void testDeleteByIds() throws IOException { //接受参数 //现在是固定数据,以后会变成动态数据 int[] ids = {4,5}; //处理参数,定义一个关键字,将查询的关键字封装 /*Brand brand = new Brand(); brand.setId(id);*/ //1. 获取SqlSessionFactory String resource = "mybatis-config.xml"; InputStream inputStream = Resources.getResourceAsStream(resource); SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream); //2.获取Sqlsession对象 //SqlSession sqlSession = sqlSessionFactory.openSession(); SqlSession sqlSession = sqlSessionFactory.openSession(true); //3.获取Mapper接口的代理对象 BrandMapper brandMapper = sqlSession.getMapper(BrandMapper.class); //4.执行方法 brandMapper.deleteByIds(ids); //5.释放资源 sqlSession.close(); }
Ps.这样也行
foreach
动态 SQL 的另一个常见使用场景是对集合进行遍历(尤其是在构建 IN 条件语句的时候)。比如:
<select id="selectPostIn" resultType="domain.blog.Post"> SELECT * FROM POST P WHERE ID in <foreach item="item" index="index" collection="list" open="(" separator="," close=")"> #{item} </foreach>
</select>标签:sqlSessionFactory,步骤,31,sqlSession,SqlSession,Brand,brand From: https://www.cnblogs.com/wangxinyuan1108/p/18225414