MyBatis通过BATCH批量提交的方法

很多人在用 MyBatis 或者 通用 Mapper 时,经常会问有没有批量插入和批量更新的方法。

实际上许多时候没必要用<foreach> 去实现特别复杂的批量操作。直接通过 MyBatis 的 BATCH 方式执行增删改方法即可。

下面是一个批量用法的例子:

@Autowired
private SqlSessionFactory sqlSessionFactory;
@Transactional(rollbackFor = Exception.class)
@Override
public void batchTest() {
  SqlSession sqlSession = sqlSessionFactory.openSession(ExecutorType.BATCH);
  CountryMapper mapper = sqlSession.getMapper(CountryMapper.class);
  List<Country> countries = mapper.selectAll();
  for (int i = 0; i < countries.size(); i++) {
    Country country = countries.get(i);
    country.setCountryname(country.getCountryname() + "Test");
    mapper.updateByPrimaryKey(country);
    //每 50 条提交一次
    if((i + 1) % 50 == 0){
      sqlSession.flushStatements();
    }
  }
  sqlSession.flushStatements();
}

在上面例子中,在Service中直接注入了SqlSessionFactory,通过下面方法获取了一个可以批量提交的SqlSession

SqlSession sqlSession = sqlSessionFactory.openSession(ExecutorType.BATCH);

后续通过SqlSession直接执行方法,或者获取的Mapper接口,都使用的批量提交方式。

上述代码执行过程中输出的日志如下:

DEBUG - Creating new transaction with name [com.isea533.mybatis.service.impl.CountryServiceImpl.batchTest]: PROPAGATION_REQUIRED,ISOLATION_DEFAULT
DEBUG - Acquired Connection [com.alibaba.druid.proxy.jdbc.ConnectionProxyImpl@752c11a2] for JDBC transaction
DEBUG - Switching JDBC Connection [com.alibaba.druid.proxy.jdbc.ConnectionProxyImpl@752c11a2] to manual commit
DEBUG - JDBC Connection [com.alibaba.druid.proxy.jdbc.ConnectionProxyImpl@752c11a2] will be managed by Spring
DEBUG - ==>  Preparing: SELECT Id,countryname,countrycode FROM country
DEBUG - ==> Parameters:
DEBUG - <==      Total: 183
DEBUG - ==>  Preparing: UPDATE country SET Id = Id,countryname = ?,countrycode = ? WHERE Id = ?
DEBUG - ==> Parameters: AngolaTest(String), AO(String), 1(Integer)
DEBUG - ==> Parameters: AfghanistanTest(String), AF(String), 2(Integer)
DEBUG - ==> Parameters: AlbaniaTest(String), AL(String), 3(Integer)
==========================================
...省略中间部分参数
==========================================
DEBUG - ==> Parameters: EthiopiaTest(String), ET(String), 50(Integer)
DEBUG - ==>  Preparing: UPDATE country SET Id = Id,countryname = ?,countrycode = ? WHERE Id = ?
DEBUG - ==> Parameters: FijiTest(String), FJ(String), 51(Integer)
DEBUG - ==> Parameters: FinlandTest(String), FI(String), 52(Integer)
==========================================
...省略中间部分参数
==========================================
DEBUG - ==> Parameters: MadagascarTest(String), MG(String), 98(Integer)
DEBUG - ==> Parameters: MalawiTest(String), MW(String), 99(Integer)
DEBUG - ==> Parameters: MalaysiaTest(String), MY(String), 100(Integer)
DEBUG - ==>  Preparing: UPDATE country SET Id = Id,countryname = ?,countrycode = ? WHERE Id = ?
DEBUG - ==> Parameters: MaldivesTest(String), MV(String), 101(Integer)
DEBUG - ==> Parameters: MaliTest(String), ML(String), 102(Integer)
==========================================
...省略中间部分参数
==========================================
DEBUG - ==> Parameters: South AfricaTest(String), ZA(String), 149(Integer)
DEBUG - ==> Parameters: SpainTest(String), ES(String), 150(Integer)
DEBUG - ==>  Preparing: UPDATE country SET Id = Id,countryname = ?,countrycode = ? WHERE Id = ?
DEBUG - ==> Parameters: Sri LankaTest(String), LK(String), 151(Integer)
DEBUG - ==> Parameters: St.LuciaTest(String), LC(String), 152(Integer)
==========================================
...省略中间部分参数
==========================================
DEBUG - ==> Parameters: ZaireTest(String), ZR(String), 182(Integer)
DEBUG - ==> Parameters: ZambiaTest(String), ZM(String), 183(Integer)
==========================================
下面事务自动提交
==========================================
DEBUG - Initiating transaction commit
DEBUG - Committing JDBC transaction on Connection [com.alibaba.druid.proxy.jdbc.ConnectionProxyImpl@752c11a2]
DEBUG - Releasing JDBC Connection [com.alibaba.druid.proxy.jdbc.ConnectionProxyImpl@752c11a2] after transaction
DEBUG - Returning JDBC Connection to DataSource

注意事项

1. 事务

由于在 Spring 集成的情况下,事务连接由 Spring 管理(SpringManagedTransaction),所以这里不需要手动关闭 sqlSession,在这里手动提交(commit)或者回滚(rollback)也是无效的。

2. 批量提交

批量提交只能应用于 insert, update, delete。

并且在批量提交使用时,如果在操作同一SQL时中间插入了其他数据库操作,就会让批量提交方式变成普通的执行方式,所以在使用批量提交时,要控制好 SQL 执行顺序。

总结

以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作具有一定的参考学习价值,谢谢大家对我们的支持。如果你想了解更多相关内容请查看下面相关链接

(0)

相关推荐

  • MyBatis-Spring配置的讲解

    MyBatis-Spring配置简单了解 SqlSessionFactoryBean配置 在基本的 MyBatis 中,session 工厂可以使用 SqlSessionFactoryBuilder 来创建.而在 MyBatis-Spring 中,则使用 SqlSessionFactoryBean 来替代. 示例 <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean&qu

  • Mybatis示例之SelectKey的应用

    SelectKey在Mybatis中是为了解决Insert数据时不支持主键自动生成的问题,他可以很随意的设置生成主键的方式. 不管SelectKey有多好,尽量不要遇到这种情况吧,毕竟很麻烦. SelectKey需要注意order属性,像Mysql一类支持自动增长类型的数据库中,order需要设置为after才会取到正确的值. 像Oracle这样取序列的情况,需要设置为before,否则会报错. 下面是一个xml和注解的例子,SelectKey很简单,两个例子就够了: <insert id=&quo

  • MyBatis常用的jdbcType数据类型

    MyBatis 通过包含的jdbcType类型 BIT FLOAT CHAR TIMESTAMP OTHER UNDEFINED TINYINT REAL VARCHAR BINARY BLOB NVARCHAR SMALLINT DOUBLE LONGVARCHAR VARBINARY CLOB NCHAR INTEGER NUMERIC DATE LONGVARBINARY BOOLEAN NCLOB BIGINT DECIMAL TIME NULL CURSOR Mybatis中javaT

  • MyBatis直接执行SQL的工具SqlMapper

    可能有些人也有过类似需求,一般都会选择使用其他的方式如Spring-JDBC等方式解决. 能否通过MyBatis实现这样的功能呢? 为了让通用Mapper更彻底的支持多表操作以及更灵活的操作,在2.2.0版本增加了一个可以直接执行SQL的新类SqlMapper. 我们来了解一下SqlMapper. SqlMapper提供的方法 SqlMapper提供了以下这些公共方法: Map<String,Object> selectOne(String sql) Map<String,Object&

  • 深入了解MyBatis参数

    深入了解MyBatis参数 相信很多人可能都遇到过下面这些异常: "Parameter 'xxx' not found. Available parameters are [...]" "Could not get property 'xxx' from xxxClass. Cause: "The expression 'xxx' evaluated to a null value." "Error evaluating expression '

  • MyBatis Map结果的Key转为驼峰式

    MyBatis 配置文件中,支持下面这几种配置: properties, settings, typeAliases, typeHandlers, objectFactory, objectWrapperFactory, reflectorFactory, plugins, environments, databaseIdProvider, mappers 我们使用objectWrapperFactory来解决这个问题. 配置这个属性时,必须遵守上面属性配置的顺序进行配置(在objectFact

  • Mybatis工具类JdbcTypeInterceptor运行时自动添加jdbcType属性

    JdbcTypeInterceptor 运行时自动添加 jdbcType 属性 拦截器签名 @Intercepts({ @Signature( type = ParameterHandler.class, method = "setParameters", args = {PreparedStatement.class}) }) 这类拦截器很少见,所以和其他拦截器(如分页插件)等搭配使用时不需要考虑顺序. 这个插件最适合的场景可能就是 Oracle 数据库,可以自动给所有方法添加 jd

  • 深入了解MyBatis二级缓存

    一.创建Cache的完整过程 我们从SqlSessionFactoryBuilder解析mybatis-config.xml配置文件开始: Reader reader = Resources.getResourceAsReader("mybatis-config.xml"); SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(reader); 然后是: XMLConfigBuilder

  • MyBatis通用Mapper实现原理及相关内容

    MyBatis通用Mapper实现原理 本文会先介绍通用 Mapper 的简单原理,然后使用最简单的代码来实现这个过程. 基本原理 通用 Mapper 提供了一些通用的方法,这些通用方法是以接口的形式提供的,例如. public interface SelectMapper<T> { /** * 根据实体中的属性值进行查询,查询条件使用等号 */ @SelectProvider(type = BaseSelectProvider.class, method = "dynamicSQL

  • Spring Boot集成MyBatis的方法

    Spring Boot 集成MyBatis 在集成MyBatis前,我们先配置一个druid数据源. Spring Boot 集成druid druid有很多个配置选项,使用Spring Boot 的配置文件可以方便的配置druid. 在application.yml配置文件中写上: spring: datasource: name: test url: jdbc:mysql://192.168.16.137:3306/test username: root password: # 使用drui

随机推荐