1. 程式人生 > >mybatis-動態刪除學習筆記

mybatis-動態刪除學習筆記

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-動態刪除學習筆記