mybatis-3 icon indicating copy to clipboard operation
mybatis-3 copied to clipboard

SqlSession seems not trigger batch operation unless I use @Transactional

Open shin8085 opened this issue 2 years ago • 3 comments

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

shin8085 avatar Mar 11 '22 06:03 shin8085

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

codeysk avatar Aug 21 '22 17:08 codeysk

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

harawata avatar Aug 22 '22 03:08 harawata

By the way, you still need @Transactional to perform batch insert. Without @Transactional, a new session will be created for each INSERT.

harawata avatar Aug 24 '22 20:08 harawata

SqlSession will not trigger batching automatically because there is no transaction context.

DaZuiZui avatar May 15 '23 16:05 DaZuiZui