目前,我正在开发一个Spring应用程序,它使用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;
}在application.properties中按如下方式配置:
# this can be externalized if necessary
mybatis.config-location=classpath:mybatis-config.xml
mybatis.executor-type=BATCH这意味着,默认情况下,mybatis将以批处理模式执行所有语句,包括单个insert/update/delete语句。这样可以吗?有什么问题我应该知道吗?
另一种方法是专门为LegMapper使用专用的LegMapper。哪种方法是最好的(专用SQLSession与application.properties中的全局设置)?
注意:我看到了其他示例,其中直接使用mybatis文件中的<foreach/>循环创建了“批插入”。我不想使用这种方法,因为它实际上没有提供批处理插入。
发布于 2021-05-09 11:17:32
正如@Ian Lim所说,如果全局将executor类型设置为BATCH,请确保使用插入和@Flush注释对映射器方法进行注释。
另一种方法是专门为LegMapper使用专用的LegMapper。哪种方法是最好的(专用SQLSession与application.properties中的全局设置)?
请记住,如果您对不同的映射程序使用不同的SQL会话,则每个SQL会话将有不同的事务。如果使用@Transactional注释的服务或服务方法使用几个使用不同SQL会话的映射器,则将分配不同的SQL事务。因此,不可能执行包含不同SQL会话的映射器的原子数据操作。
https://stackoverflow.com/questions/53934066
复制相似问题