mybatis-3
mybatis-3 copied to clipboard
SqlSession seems not trigger batch operation unless I use @Transactional
MyBatis version
3.5.9
Database vendor and version
SQLServer 2019 15.0.4198.2
Test case or example project
@Component
public class DataTest {
@Resource
private SqlSessionFactory sqlSessionFactory;
// @Transactional
public void add(List<Data> itemList) {
SqlSession session = sqlSessionFactory.openSession(ExecutorType.BATCH, false);
DataMappermapper = session.getMapper(DataMapper.class);
for (int i = 0; i < itemList.size(); i++) {
mapper.insert(itemList.get(i));
}
session.commit();
session.clearCache();
}
}
class DataSyncApplicationTests {
@Resource
DataTest dataTest;
@Test
void contextLoads() throws Exception {
StopWatch stopWatch=new StopWatch();
List<Data> list=new ArrayList<>();
for(int i=0;i<50000;i++){
Data data=new Data();
data.setId("test:"+i);
data.setRemark("new");
data.setResult("new");
data.setClueId("nddd");
data.setOwnerName("ffff");
data.setAudioUrl("fffff");
list.add(data);
}
stopWatch.start();
dataTest.add(list); //invoke
stopWatch.stop();
System.out.println(stopWatch.getLastTaskTimeMillis());
}
}
Steps to reproduce
When I run this code it took me 42091ms, but if I add @Transactional to my method before run it that it's only spend 4930ms.
Expected result
take less time and don't neet @Transactional, there seems to have been some transaction operations in SqlSession but I don't sure it is work
Actual result
it need @Transactional
I also had this problem and found that the autoCommit value in the Connection obtained through the proxy object was still true and needed to be manually set to false
Please read the mybatis-spring documentation. https://mybatis.org/spring/ A sample code with BATCH executor type and its limitation is explained in this page. https://mybatis.org/spring/sqlsession.html
By the way, you still need @Transactional
to perform batch insert.
Without @Transactional
, a new session will be created for each INSERT.
SqlSession will not trigger batching automatically because there is no transaction context.