mybatis-动态删除学习笔记
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了mybatis-动态删除学习笔记相关的知识,希望对你有一定的参考价值。
java
import java.util.ArrayList;
import java.util.List;
import org.apache.ibatis.session.SqlSession;
import cn.itcast.javaee.mybatis.util.MybatisUtil;
/**
* 持久层
* @author AdminTC
*/
public class StudentDao {
/**
* 根据ID批量删除学生(数组版本)
*/
public void dynaDeleteArray(int... ids) throws Exception{
SqlSession sqlSession = null;
try{
sqlSession = MybatisUtil.getSqlSession();
sqlSession.delete("studentNamespace.dynaDeleteArray",ids);
sqlSession.commit();
}catch(Exception e){
e.printStackTrace();
sqlSession.rollback();
throw e;
}finally{
MybatisUtil.closeSqlSession();
}
}
/**
* 根据ID批量删除学生(集合版本)
*/
public void dynaDeleteList(List<Integer> ids) throws Exception{
SqlSession sqlSession = null;
try{
sqlSession = MybatisUtil.getSqlSession();
sqlSession.delete("studentNamespace.dynaDeleteList",ids);
sqlSession.commit();
}catch(Exception e){
e.printStackTrace();
sqlSession.rollback();
throw e;
}finally{
MybatisUtil.closeSqlSession();
}
}
public static void main(String[] args) throws Exception{
StudentDao dao = new StudentDao();
//dao.dynaDeleteArray(new int[]{1,3,5,7,77});
//dao.dynaDeleteArray(1,3,5,7,77);
//dao.dynaDeleteArray(2,4,444);
List<Integer> ids = new ArrayList<Integer>();
ids.add(6);
ids.add(8);
ids.add(9);
dao.dynaDeleteList(ids);
}
}
xml
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="studentNamespace">
<resultMap type="cn.itcast.javaee.mybatis.app13.Student" id="studentMap">
<id property="id" column="students_id"/>
<result property="name" column="students_name"/>
<result property="sal" column="students_sal"/>
</resultMap>
<delete id="dynaDeleteArray">
delete from students where students_id in
<!-- foreach用于迭代数组元素
open表示开始符号
close表示结束符合
separator表示元素间的分隔符
item表示迭代的数组,属性值可以任意,但提倡与方法的数组名相同
#{ids}表示数组中的每个元素值
-->
<foreach collection="array" open="(" close=")" separator="," item="ids">
#{ids}
</foreach>
</delete>
<delete id="dynaDeleteList">
delete from students where students_id in
<foreach collection="list" open="(" close=")" separator="," item="ids">
#{ids}
</foreach>
</delete>
</mapper>
以上是关于mybatis-动态删除学习笔记的主要内容,如果未能解决你的问题,请参考以下文章