Mybatis批量插入、批量删除

一)Mybatis 标签

foreach元素的属性主要有 item,index,collection,open,separator,close

item:表示集合中每一个元素进行迭代时的别名

index:指定一个名字,用于表示在迭代过程中,每次迭代到的位置

collection

    如果传入的参数类型是一个List时,collection属性值为list

    如果传入的参数类型是一个array数组时,collection的属性值为array

    如果传入的参数是多个时,可把参数封装成一个Map

open:表示该语句以什么开始

separator:表示该语句在每次进行迭代之间以什么符号作为分隔符

close:表示该语句以什么结束

 

二)Mybatis批量插入

方式一:单条新增,批次提交

xml代码:


    insert into tab_employee(emp_id,emp_name,emp_no,create_date)
    values(#{empId}, #{empName}, #{empNO}, #{createDate})

DAO接口:

int addEmployee(EmployeeEntity entity);

insert代码:

package com.oysept.test;

import java.util.Date;

import org.apache.ibatis.session.SqlSession;

import com.oysept.dao.EmployeeDAO;
import com.oysept.entity.EmployeeEntity;
import com.oysept.utils.SessionUtils;

public class AddEmployeeTest {

    public static void main(String[] args) {
        SqlSession sqlSession = null;
        try {
            long beginTime = System.currentTimeMillis();
            sqlSession = SessionUtils.getSqlSessionFactory().openSession();
            // 初始化DAO接口
            EmployeeDAO employeeDAO = sqlSession.getMapper(EmployeeDAO.class);
			
            EmployeeEntity entity = null;
            for (int i = 0; i < 500; i++) {
                entity = new EmployeeEntity();
                entity.setEmpId(100000 + i);
                entity.setEmpName("ouyangjun");
                entity.setEmpNO("333333");
                entity.setCreateDate(new Date().getTime());
				
                // 持久化
                employeeDAO.addEmployee(entity);
            }
            // 提交事务
            sqlSession.commit();
            long endTime = System.currentTimeMillis();
            System.out.println("==>员工数据持久化成功!, 总耗时" + (endTime-beginTime) + "毫秒!");
        } catch (Exception e){
            e.printStackTrace();
            sqlSession.rollback();
            System.out.println("==>员工数据持久化失败!");
        } finally {
            sqlSession.close();
            System.out.println("==>事务关闭!");
        }
    }
}

 

方式二:批量新增,分批提交

mysql批次新增sql语法:

insert into tablename (column1,column2) values
('aa','bb'),
('dd','cc'),
('ee','ff');

oracle批次新增sql语法:

insert all into tablename (column1,column2) values ('aa','bb')
into tablename (column1,column2) values ('dd','cc')
into tablename (column1,column2) values ('ee,'ff')
select 1 from dual;

xml代码:

collection="list":表示java.util.List集合

collection="array":表示数组


    insert all
    
        into tab_employee(emp_id,emp_name,emp_no,create_date) values (#{item.empId}, #{item.empName}, #{item.empNO}, #{item.createDate})
    
    select 1 from dual

DAO接口:

int batchInsertEmployee(List entityList);

insert代码:

原理:将实体类数据先用一个List集合存储,分批处理新增的数据并提交事务,然后清除集合,关闭数据库连接。

package com.oysept.test;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.apache.ibatis.session.SqlSession;

import com.oysept.dao.EmployeeDAO;
import com.oysept.entity.EmployeeEntity;
import com.oysept.utils.SessionUtils;

public class BatchInsertEmployee {

    public static void main(String[] args) {
        SqlSession sqlSession = null;
        try {
            long beginTime = System.currentTimeMillis();
            sqlSession = SessionUtils.getSqlSessionFactory().openSession();
            // 加载DAO接口
            EmployeeDAO employeeDAO = sqlSession.getMapper(EmployeeDAO.class);
			
            int batchSize = 100; // 批次
            // 初始化
            List entityList = new ArrayList(batchSize+1); // 初始化集合大小, 避免集合自动扩容, 消耗性能
            EmployeeEntity entity = null;
            for (int i = 0; i < 5000; i++) {
                entity = new EmployeeEntity();
                entity.setEmpId(100000 + i);
                entity.setEmpName("ouyangjun");
                entity.setEmpNO("333333");
                entity.setCreateDate(new Date().getTime());
				
                entityList.add(entity); // 添加到集合中
				
                if (i > 0 && i % batchSize == 0) { // 分批次提交事务
                    System.out.println("==>第" + (i/batchSize) + "次提交事务!");
                    // 持久化
                    employeeDAO.batchInsertEmployee(entityList);
                    sqlSession.commit(); // 提交事务, 如不提交事务, 当jvm回收时, 数据不会持久化到数据库中
                    entityList.clear(); // 清理数据
                }
            }
            // 提交最后一批可能不满100条的数据
            employeeDAO.batchInsertEmployee(entityList);
            sqlSession.commit(); // 提交事务, 如不提交事务, 当jvm回收时, 数据不会持久化到数据库中
            entityList.clear(); // 清理数据
			
            long endTime = System.currentTimeMillis();
            System.out.println("==>员工数据持久化成功!, 总耗时" + (endTime-beginTime) + "毫秒!");
        } catch (Exception e){
            e.printStackTrace();
            sqlSession.rollback();
            System.out.println("==>员工数据持久化失败!");
        } finally {
            sqlSession.close();
            System.out.println("==>事务关闭!");
        }
    }
}

 

三)Mybatis批量删除

方式一:传入List

xml代码:


    delete from tab_employee where 1=1
    and emp_Id in 
    
        #{item}
    

DAO接口:

int deleteEmployeeEntityByEmpId(String[] empIds);

delete代码:

package com.oysept.test;

import java.io.IOException;

import org.apache.ibatis.session.SqlSession;

import com.oysept.dao.EmployeeDAO;
import com.oysept.utils.SessionUtils;

public class DeleteEmployeeTest {

    public static void main(String[] args) throws IOException {
        SqlSession sqlSession = null;
        try {
            sqlSession = SessionUtils.getSqlSessionFactory().openSession();
            // 初始化DAO接口
            EmployeeDAO employeeDAO = sqlSession.getMapper(EmployeeDAO.class);
			
            String[] empIds = {"100000","200000"};
            employeeDAO.deleteEmployeeEntityByEmpId(empIds);
			
            sqlSession.commit();
            System.out.println("==>员工数据删除成功!");
        } catch (Exception e){
            e.printStackTrace();
            sqlSession.rollback();
            System.out.println("==>员工数据删除失败!");
        } finally {
            sqlSession.close();
            System.out.println("==>事务关闭!");
        }
    }
}

 

方式二:传入Map

xml代码:


    delete from tab_employee 
    
        
            and emp_Id in 
            
                #{item}
            
        
        
            and emp_name = (#{mapKey.empNames,jdbcType=VARCHAR})
        
    

DAO接口:

int deleteEmployeeByMap(@Param("mapKey") Map mapKey);

delete代码:

注意:Map中value的参数类型要和数据库类型对上

package com.oysept.test;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import org.apache.ibatis.session.SqlSession;

import com.oysept.dao.EmployeeDAO;
import com.oysept.utils.SessionUtils;

public class MapDeleteEmployeeTest {

    public static void main(String[] args) throws IOException {
        SqlSession sqlSession = null;
        try {
            sqlSession = SessionUtils.getSqlSessionFactory().openSession();
            // 初始化DAO接口
            EmployeeDAO employeeDAO = sqlSession.getMapper(EmployeeDAO.class);
			
            Map mapKey = new HashMap();
            mapKey.put("empIds", new Integer[]{308006, 877192});
            mapKey.put("empNames", "ouyangjun");
            int count = employeeDAO.deleteEmployeeByMap(mapKey);
			
            sqlSession.commit();
            System.out.println("==>员工数据删除成功! 总删除" + count + "条数据!");
        } catch (Exception e){
            e.printStackTrace();
            sqlSession.rollback();
            System.out.println("==>员工数据删除失败!");
        } finally {
            sqlSession.close();
            System.out.println("==>事务关闭!");
        }
    }
}

数据类型对应图:

Mybatis批量插入、批量删除_第1张图片

 

识别二维码关注个人微信公众号

本章完结,待续,欢迎转载!
 
本文说明:该文章属于原创,如需转载,请标明文章转载来源!

你可能感兴趣的:(Mybatis)