【问题标题】:Is it OK to globally set the mybatis executor mode to BATCH?全局设置mybatis执行器模式为BATCH可以吗?
【发布时间】:2018-12-26 15:38:01
【问题描述】:

我目前正在开发一个 Spring Boot 应用程序,它使用 mybatis 作为其持久层。我想在以下场景中优化实体的批量插入:

// flightSerieMapper and legMapper are used to create a series of flights.
// legMapper needs to use batch insertion.
@Transactional
    public FlightSerie add(FlightSerie flightSerie) {
        Integer flightSerieId = flightSeriesSequenceGenerator.getNext();
        flightSerie.setFlightSerieId(flightSerieId);
        flightSerieMapper.create(flightSerie);
        // create legs in batch mode
        for (Leg leg : flightSerie.getFlightLegs()) {
            Integer flightLegId = flightLegsSequenceGenerator.getNext();
            leg.setLegId(flightLegId);
            legMapper.create(leg);
        }
        return flightSerie;
    }

mybatis在application.properties中配置如下:

# this can be externalized if necessary
mybatis.config-location=classpath:mybatis-config.xml
mybatis.executor-type=BATCH

这意味着mybatis默认会以批处理方式执行所有语句,包括单个insert/update/delete语句。这个可以吗?有什么我应该注意的问题吗?

另一种方法是使用专门用于 LegMapper 的专用 SQLSession。哪种方法最好(专用 SQLSession 与 application.properties 中的全局设置)?

注意:我看到了其他示例,其中直接在 mybatis xml 映射器文件中使用 <foreach/> 循环创建“批量插入”。我不想使用这种方法,因为它实际上并没有提供批量插入。

【问题讨论】:

  • 您必须确保为所有插入和更新执行刷新(带有@Flush 注释的方法)。
  • 谢谢伊恩。如果您添加您的评论作为答案,我会接受它

标签: mybatis spring-mybatis


【解决方案1】:

正如@Ian Lim 所说,如果您将执行器类型全局设置为BATCH,请确保您使用插入和更新使用@Flush 注释来注释映射器方法。

另一种方法是专门使用专用的 SQLSession 对于 LegMapper。哪种方法最好(专用 SQLSession 与 application.properties 中的全局设置)?

请记住,如果您为不同的映射器使用不同的 SQL 会话,则每个 SQL 会话将有不同的事务。如果使用 @Transactional 注释的服务或服务方法使用多个使用不同 SQL 会话的映射器,它将分配不同的 SQL 事务。因此,不可能进行涉及具有不同 SQL 会话的映射器的原子数据操作。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-03-05
    • 1970-01-01
    • 2014-10-06
    • 2011-06-30
    • 2014-10-26
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多