文章目录
按照id删除单个记录
接口建方法
void deleteById(int id);
生成映射语句
<delete id="deleteById">
delete from mybatis.brand
where id = #{id}
</delete>
执行代码
@Test
public void testDelById() throws IOException {
String resource = "mybatis-config.xml";
InputStream inputStream = Resources.getResourceAsStream(resource);
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
SqlSession sqs = sqlSessionFactory.openSession();
BrandMapper mapper = sqs.getMapper(BrandMapper.class);
int id = 6;
mapper.deleteById(id);
sqs.commit();
sqs.close();
}


文章目录
批量删除,不确定删除几个
添加方法,参数传递有两种写法,对应映射的写法
void delByIds(int[] ids);
// void delByIds(@Param("ids")int[] ids);
映射
<delete id="delByIds">
delete from mybatis.brand
where id in
<!--mybatis收到复数id的数组int[],会封装成一个Map集合,键名默认叫array,所以foreach里写array
而不是ids,如果想写ids,在方法的参数那里用@Param("ids")注解-->
<foreach collection="array" item="id" separator="," open="(" close=")">
#{id}
</foreach>
</delete>
执行代码
@Test
public void testDelByIds() throws IOException {
String resource = "mybatis-config.xml";
InputStream inputStream = Resources.getResourceAsStream(resource);
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
SqlSession sqs = sqlSessionFactory.openSession();
BrandMapper mapper = sqs.getMapper(BrandMapper.class);
int[] ids = {2,3};
mapper.delByIds(ids);
sqs.commit();
sqs.close();
}
结果



本文介绍了使用MyBatis进行数据库增删改查的实践,详细讲解了映射语句的生成及代码执行过程,通过实例展示了如何在Java中操作数据库。
614

被折叠的 条评论
为什么被折叠?



