MyBatis 九 ——删除一个/删除多个
删除一个
1、编写接口方法:Mapper接口
观察参数
返回结果
2、编写SQL语句:SQL映射文件;
3:执行方法,测试
//删除 @Test public void testDeleteById() throws IOException { int id = 10; int status =1; String companyName = "波导手机"; String brandName = "波导"; String description = "???"; String ordered = "21000"; Brand brand = new Brand(); brand.setStatus(status); brand.setBrandName(brandName); brand.setCompanyName(companyName); brand.setDescription(description); brand.setOrdered(ordered); 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(true); //3 获取Mapper接口的代理对象 BrandMapper brandMapper = sqlSession.getMapper(BrandMapper.class); //4 执行方法 brandMapper.deleteById(id); //5 释放资源 sqlSession.close(); }
批量删除:
1、编写接口方法:Mapper接口
观察参数
返回结果
2、编写SQL语句:SQL映射文件;
或者
3:执行方法,测试
//删除多个 @Test public void testDeleteByIds() throws IOException { int[] ids= {5,7,11}; //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(); }
<!-- 修改-->
<update id="update">
update tb_brand
<set>
<if test="brandName != null and brandName != ''">
brand_name = #{brandName},
</if>
<if test="companyName != null and companyName != ''">
company_name = #{companyName},
</if>
<if test="ordered != null and ordered !=''">
ordered = #{ordered},
</if>
<if test="description != null and description != ''">
description = #{description},
</if>
<if test="status != null ">
status = #{status}
</if>
</set>
where id = #{id}
</update>
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 分享4款.NET开源、免费、实用的商城系统
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
· 记一次.NET内存居高不下排查解决与启示