码迷,mamicode.com
首页 > 数据库 > 详细

MyBatis的动态SQL操作--删除

时间:2016-03-24 13:02:23      阅读:156      评论:0      收藏:0      [点我收藏+]

标签:

技术分享

根据选择条目的不同生成不同的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);
    }
}

 

MyBatis的动态SQL操作--删除

标签:

原文地址:http://www.cnblogs.com/winner-0715/p/5314840.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!