删除一个数据
在mapper中定义删除的方法
public interface StudentMapper {
//定义删除的方法
void deleteById(int ID);
}
编写xml
<delete id="delectByid">
delete from studentinformation where id=#{ID};
</delete>
测试
@Test
public void test02() throws IOException {
String resource = "mybatis-config.xml";
InputStream inputStream = Resources.getResourceAsStream(resource);
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
//获取SqlSession对象,用来执行sql
SqlSession sqlSession=sqlSessionFactory.openSession();
StudentMapper mapper = sqlSession.getMapper(StudentMapper.class);
mapper.delectByid(74);
//提交事务
sqlSession.commit();
}
批量删除
定义mapper接口
public interface StudentMapper {
//定义删除的方法
void deleteByIds(@Param("ids") int[] ids);
}
SQL映射文件
<!--
mybatis 会将数组参数,封装为一个 Map集合
默认:array =数组
使用 @Param 注解变map集合的默认key的名称
-->
<delete id="delectBylds">
delete from studentinformation
where id in
<foreach collection="ids" item="id" separator="," open="(" close=")">
#{id}
</foreach>
</delete>
<!--
上面的SQL语句相当于
delect from studentinformation where id in (?,?,?)
-->
<!--
collection 表示 传进来的数组,这里使用@Param将array改为ids item 表示索引 separator 表 示分隔符 open 表示 开始( close 表示 结束)
-->
测试
@Test
public void Test03() throws IOException {
String resource = "mybatis-config.xml";
InputStream inputStream = Resources.getResourceAsStream(resource);
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
//获取SqlSession对象,用来执行sql
SqlSession sqlSession=sqlSessionFactory.openSession();
StudentMapper mapper = sqlSession.getMapper(StudentMapper.class);
int[] ids={12,23,34,5}
mapper.delectBylds(ids);
//提交事务
sqlSession.commit();
}