Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
617 views
in Technique[技术] by (71.8m points)

Spring-MyBatis - How to achieve transaction Rollback for method having both batch and simple query execution?

I have a Spring Boot application with MyBatis mapper DAO layer. I have a method call (serviceA.insert(records)) which performs

  1. batch insertion(~ 1000records) using ExecutorType.BATCH - Manual session management
  2. simple insertion(1 record) using ExecutorType.SIMPLE by calling another serviceB from serviceA.insert(records) - automatic session management by spring

to 2 different tables using 2 different SqlSession factories and DAOs.

Service A:

  public class serviceA{
    
      public void insert(List<String> records){
        
                SqlSession sqlSession = sqlSessionFactory.openSession(ExecutorType.BATCH);
                TestDao mapper = sqlSession.getMapper(TestDao.class);
        
               try {
                    int size = 50;
                    for (int i = 0; i < size; ) {
    
                        mapper.insertA(records[i]);   //line 1 - batch execution
        
                        i++;
                        if (i % batchSize == 0 || i == size1) {
                            sqlSession.flushStatements();
                            sqlSession.clearCache();
                        }
                    }
                    sqlSession.commit();
        
                } catch (Exception e) {
                    sqlSession.rollback();
                    log.error("Insertion error ", e);
                } finally {
                    sqlSession.close();
                }
        
               serviceB.insertBy("Helen"); 
        
        }
    
    }

Service B:

   public class ServiceB{
    
     @Autowired 
     DaoB daoB;   //mapper with executorType.Simple 
    
     public void insertBy(String name){
        // business logic

        daoB.insertBy(name); //line 2 - simple execution
       }
    }

If some error happens in line2/serviceB , line1 also should rollback. How can it be achieved? If I use @Transactional also, am manually managing sessions for batch execution in service A, so I guess that won't work as expected.

Please help to achieve rollback in this case.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
等待大神答复

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...