【发布时间】: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 注释的方法)。
-
谢谢伊恩。如果您添加您的评论作为答案,我会接受它