使用 Spring Transaction with Mybatis batch
Using Spring Transaction with Mybatis batch
我有一个 @Transactional
方法,它在一个公共 spring bean 上调用另一个方法,该 bean 长期以来一直用于执行 batch
操作, 跨映射器。现在的问题是,如果 @Transactional
方法中存在 error,则在 batch
上执行的 DML 不会回滚,因为它们是在一个不同的会话,有自己的事务。
public class HamsterRepo{
...
@Autowired
BatchOperationBean<Hamsters> idioticBatchBean;
@Transactional
public void saveHamsters(List<Hamsters> hams){
idioticBatchBean.executebatch("saveHamsters", hams);
}
}
public class BatchOperationBean<T>{
@Autowired
SqlSessionFactory sqlFactory;
public void executebatch(String mapperId, List<T> ts){
SqlSession sqlSession =
this.sqlSessionFactory.openSession(ExecutorType.BATCH,
TransactionIsolationLevel.SERIALIZABLE);
try(sqlSession){
for(T t in ts){
sqlSession.update(mapperId , t);
}
sqlSession.commit();
// Clean Up stuff and Exception Handling...
}
}
}
现在,有没有办法将两者联系起来 Spring Tx and SqlSessionFactory
?注入 SqlSession 而不是工厂有帮助吗?或者有没有办法从 Spring Tx 获取 SqlSession?或者 Spring 中的一种方法,可以在没有 SqlSesion 的情况下跨映射器识别和执行查询?
PS:使用Spring 4.1.7,Mybatis:3.4.4,Mybatis-spring:1.3.1
貌似linkSpring事务和Mybatis SqlSession的方式是SqlSessionTemplate
Thread safe, Spring managed, SqlSession that works with Spring transaction management to ensure that that the actual SqlSession used is the one associated with the current Spring transaction. In addition, it manages the session life-cycle, including closing, committing or rolling back the session as necessary based on the Spring transaction configuration.
我有一个 @Transactional
方法,它在一个公共 spring bean 上调用另一个方法,该 bean 长期以来一直用于执行 batch
操作, 跨映射器。现在的问题是,如果 @Transactional
方法中存在 error,则在 batch
上执行的 DML 不会回滚,因为它们是在一个不同的会话,有自己的事务。
public class HamsterRepo{
...
@Autowired
BatchOperationBean<Hamsters> idioticBatchBean;
@Transactional
public void saveHamsters(List<Hamsters> hams){
idioticBatchBean.executebatch("saveHamsters", hams);
}
}
public class BatchOperationBean<T>{
@Autowired
SqlSessionFactory sqlFactory;
public void executebatch(String mapperId, List<T> ts){
SqlSession sqlSession =
this.sqlSessionFactory.openSession(ExecutorType.BATCH,
TransactionIsolationLevel.SERIALIZABLE);
try(sqlSession){
for(T t in ts){
sqlSession.update(mapperId , t);
}
sqlSession.commit();
// Clean Up stuff and Exception Handling...
}
}
}
现在,有没有办法将两者联系起来 Spring Tx and SqlSessionFactory
?注入 SqlSession 而不是工厂有帮助吗?或者有没有办法从 Spring Tx 获取 SqlSession?或者 Spring 中的一种方法,可以在没有 SqlSesion 的情况下跨映射器识别和执行查询?
PS:使用Spring 4.1.7,Mybatis:3.4.4,Mybatis-spring:1.3.1
貌似linkSpring事务和Mybatis SqlSession的方式是SqlSessionTemplate
Thread safe, Spring managed, SqlSession that works with Spring transaction management to ensure that that the actual SqlSession used is the one associated with the current Spring transaction. In addition, it manages the session life-cycle, including closing, committing or rolling back the session as necessary based on the Spring transaction configuration.