标签:
根据选择条目的不同生成不同的sql语句来删除不同的条目.
delete from student where id in (1, 3, 5)
<?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"> <!-- namespace的取值可以是实体的全限定名,这样有好处! --> <mapper namespace="com.tuniu.entity.Student"> <resultMap id="studentMap" type="student"> <id property="id" column="id"/> <result property="name" column="name"/> <result property="sal" column="sal"/> </resultMap> <delete id="dynaDeleteArray"> delete from student where id in <!-- foreach用于迭代数组元素 open表示开始符号 close表示结束符合 separator表示元素间的分隔符 item表示迭代的数组,属性值可以任意,但提倡与方法的数组名相同 #{ids}表示数组中的每个元素值 --> <foreach collection="array" open="(" close=")" separator="," item="ids"> #{ids} </foreach> </delete> <delete id="dynaDeleteList"> delete from student where id in <foreach collection="list" open="(" close=")" separator="," item="ids"> #{ids} </foreach> </delete> </mapper>
public class StudentDao { /** * 根据ID批量删除(数组) */ public void dynaDeleteArray(int... ids) throws Exception{ SqlSession sqlSession = null; try{ sqlSession = MybatisUtil.getSqlSession(); sqlSession.delete(Student.class.getName() + ".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(Student.class.getName() + ".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); } }
标签:
原文地址:http://www.cnblogs.com/winner-0715/p/5314840.html