javaweb--mybatis删除功能

发布时间 2023-11-06 17:19:36作者: na2co3-

 批量删除

mybatis会将数组自动封装为Map集合,所以在接口函数处使用@Param注解改变map集合的默认key名称

不使用的话可以用默认名array

接口函数:

使用了@Param改变了默认的array的名称

int deleteByIds(@Param("ids") int[] ids);

mysql映射函数 collection名为ids,如果没有使用@Param则为默认的array

 <delete id="deleteByIds">
        delete from tb_brand where id
        in
        <foreach collection="ids" item="id" separator="," open="(" close=")">
            #{id}
        </foreach>
        ;
    </delete>

执行文件

@Test
    public void DeleteByIds() throws IOException {
        //接收变量

        int[] ids = {6,7};
        //String brandname = "";
        //处理数据
        //companyname = "%" + companyname + "%";
        //brandname = "%" + brandname + "%";

        //封装类


/*        Map map = new HashMap();
        map.put("status",status);
        map.put("companyname",companyname);
        map.put("brandname",brandname);*/
        //1、获取sqlSessionFactory
        String rescource = "mybatis-config.xml";
        InputStream inputStream = Resources.getResourceAsStream(rescource);
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
        //2、获取SqlSession对象
        SqlSession sqlSession = sqlSessionFactory.openSession();
        //3、获取Mapper接口的代理对象
        BrandMapper brandMapper = sqlSession.getMapper(BrandMapper.class);
        //4、执行方法

        int count = brandMapper.deleteByIds(ids);
        sqlSession.commit();
        //
        //List<Brand> brands = brandMapper.selectBycondition(map);
        System.out.println(count);
        //5、释放资源
        sqlSession.close();

    }