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>
原文地址:http://blog.51cto.com/357712148/2107437
时间: 2024-10-19 18:31:37