mybatis 批量操作数据

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了mybatis 批量操作数据相关的知识,希望对你有一定的参考价值。

参考技术A

mybatis的批量操作有两种方式,一是使用foreach标签,二是使用mybatis的BATCH模型

在xml中通过foreach对表数据进行循环操作

在oracle中不支持insert into product(name, type, price) values (\'a\', \'tv\', 1233), (\'b\', \'ac\', 3455),....(\'\',\'\',\'\')这种形式的sql,因此oracle批量插入使用 insert all into table(...) values(...) into table(...) values(...) select * from dual; 语句来解决以下方式,并且需要显示指定useGeneratedKeys=false

另一种方法是使用另外一种方法是 insert into table(...) (select ... from dual) union all (select ... from dual)

Mybatis内置的ExecutorType一共有三种,默认为SIMPLE,该模式下它为每个语句的执行创建一个新的预处理语句,并单条提交sql。

BATCH 模式会重复使用已经预处理的语句,并且批量执行所有更新语句,显然batch性能将更优;
注意 : batch模式也有自己的问题,比如在Insert操作时,在事务没有提交之前,是没有办法获取到自增的id,这在某型情形下是不符合业务要求的。
具体用法如下:

ProductMapper.java 如下:

mapper.xml 如下:

Mybatis批量操作

一、批量操作

      1、添加依赖包,参考上篇文章 Mybatis+mysql入门使用

      2、初始化数据库和初始数据,以mysql为例

DROP DATABASE IF EXISTS moy_mybatis;
CREATE DATABASE moy_mybatis CHARACTER SET UTF8;
USE moy_mybatis;

DROP TABLE  IF EXISTS t_test;

CREATE TABLE t_test(
    id int(11) AUTO_INCREMENT,
    create_time DATE comment \'创建时间\',
    modify_time DATE comment \'修改时间\',
    content VARCHAR (50) comment \'内容\',
    PRIMARY KEY (id)
);
View Code

      3、新建实体类TestEntity

package com.moy.mybatis3.entity;

import java.util.Date;

/**
 * [Project]:moy-gradle-project  <br/>
 * [Email]:moy25@foxmail.com  <br/>
 * [Date]:2018/2/20  <br/>
 * [Description]:  <br/>
 *
 * @author YeXiangYang
 */
public class TestEntity {
    private Integer id;
    private Date createTime;
    private Date modifyTime;
    private String content;

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public Date getCreateTime() {
        return createTime;
    }

    public void setCreateTime(Date createTime) {
        this.createTime = createTime;
    }

    public Date getModifyTime() {
        return modifyTime;
    }

    public void setModifyTime(Date modifyTime) {
        this.modifyTime = modifyTime;
    }

    public String getContent() {
        return content;
    }

    public void setContent(String content) {
        this.content = content;
    }

    @Override
    public String toString() {
        return "TestEntity{" +
                "id=" + id +
                ", createTime=" + createTime +
                ", modifyTime=" + modifyTime +
                ", content=\'" + content + \'\\\'\' +
                \'}\';
    }
}
View Code

      4、新建实体对应配置文件Test.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="com.moy.mybatis3.mapper.TestMapper">
    <delete id="deleteBatch">
        delete FROM t_test WHERE id in (
        <foreach collection="array" item="id" separator=",">
            #{id}
        </foreach>
        )
    </delete>

    <insert id="insertBatch">
        INSERT INTO t_test (create_time,modify_time,content)
        VALUES
        <foreach collection="list" item="TestEntity" separator=",">
            (#{TestEntity.createTime},#{TestEntity.modifyTime},#{TestEntity.content})
        </foreach>
    </insert>
</mapper>
View Code

      5、编写接口TestMapper

package com.moy.mybatis3.mapper;

import com.moy.mybatis3.entity.TestEntity;

import java.io.Serializable;
import java.util.List;

/**
 * [Project]:moy-gradle-project  <br/>
 * [Email]:moy25@foxmail.com  <br/>
 * [Date]:2018/2/20  <br/>
 * [Description]:  <br/>
 *
 * @author YeXiangYang
 */
public interface TestMapper {

    int insertBatch(List<TestEntity> list);

    int deleteBatch(Serializable[] id);
}
View Code

      6、为了方便测试,编写一个获取SqlSession的工具类Mybatis3Utils

package com.moy.mybatis3.utils;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import java.io.IOException;
import java.io.Reader;
import java.util.Objects;

/**
 * [Project]:moy-gradle-project  <br/>
 * [Email]:moy25@foxmail.com  <br/>
 * [Date]:2018/2/19  <br/>
 * [Description]:  <br/>
 *
 * @author YeXiangYang
 */
public abstract class Mybatis3Utils {

    public static final SqlSessionFactory sqlSessionFactory;
    public static final ThreadLocal<SqlSession> sessionThread = new ThreadLocal<>();

    static {
        try {
            Reader reader = Resources.getResourceAsReader("mybatis-config.xml");
            sqlSessionFactory = new SqlSessionFactoryBuilder().build(reader);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    public static SqlSession getCurrentSqlSession() {
        SqlSession sqlSession = sessionThread.get();
        if (Objects.isNull(sqlSession)) {
            sqlSession = sqlSessionFactory.openSession();
            sessionThread.set(sqlSession);
        }
        return sqlSession;
    }

    public static void closeCurrentSession() {
        SqlSession sqlSession = sessionThread.get();
        if (Objects.nonNull(sqlSession)) {
            sqlSession.close();
        }
        sessionThread.set(null);
    }
}
View Code

      7、新建mybatis配置信息文件mybatis-config.xml

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
        PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>

    <settings>
        <setting name="logImpl" value="STDOUT_LOGGING"/>
    </settings>

    <typeAliases>
        <package name="com.moy.mybatis3.entity"/>
    </typeAliases>

    <environments default="development">
        <environment id="development">
            <transactionManager type="JDBC"/>
            <dataSource type="POOLED">
                <property name="driver" value="com.mysql.jdbc.Driver"/>
                <property name="url" value="jdbc:mysql://127.0.0.1:3306/moy_mybatis?useSSL=false"/>
                <property name="username" value="root"/>
                <property name="password" value="123"/>
            </dataSource>
        </environment>
    </environments>

    <mappers>
        <mapper resource="mapper/Test.xml"></mapper>
    </mappers>
</configuration>
View Code

      8、编写测试类TestMapperTest

package com.moy.mybatis3.mapper;

import com.moy.mybatis3.entity.TestEntity;
import com.moy.mybatis3.utils.Mybatis3Utils;
import org.apache.ibatis.session.SqlSession;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;

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

import static org.junit.Assert.*;

/**
 * [Project]:moy-gradle-project  <br/>
 * [Email]:moy25@foxmail.com  <br/>
 * [Date]:2018/2/20  <br/>
 * [Description]:  <br/>
 *
 * @author YeXiangYang
 */
public class TestMapperTest {

    SqlSession sqlSession;
    TestMapper testMapper;

    @Before
    public void before() {
        sqlSession = Mybatis3Utils.getCurrentSqlSession();
        testMapper = sqlSession.getMapper(TestMapper.class);
    }

    @After
    public void after() {
        Mybatis3Utils.closeCurrentSession();
    }

    @Test
    public void insertBatch() {
        int count = 10;
        List<TestEntity> list = new ArrayList<>(count);
        for (int i = 0; i < count; i++) {
            TestEntity entity = new TestEntity();
            entity.setCreateTime(new Date());
            entity.setModifyTime(new Date());
            entity.setContent("我是批量添加的内容");
            list.add(entity);
        }
        System.out.println(testMapper.insertBatch(list));
        sqlSession.commit();
    }

    @Test
    public void deleteBatch() {
        int count = 10;
        Integer[] array = new Integer[count];
        for (int i = 0; i < count; i++) {
            array[i] = i + 1;
        }
        System.out.println(testMapper.deleteBatch(array));
        sqlSession.commit();
    }
}
View Code

 

yexiangyang

moyyexy@gmail.com


 

以上是关于mybatis 批量操作数据的主要内容,如果未能解决你的问题,请参考以下文章

Mybatis批量操作

MyBatis # 使用mybatis批量操作数据,提升效率

MyBatis学习总结_10_批量操作

on duplicate key update 的用法说明(解决批量操作数据,有就更新,没有就新增)mybatis批量操作数据更新和添加

数据库--MyBatis的(insert,update,delete)三种批量操作

MyBatis批量新增和更新