>我有一个@Transactional
方法,它在一个普通的春豆上调用另一个方法,该方法长期以来一直用于跨映射器执行batch
操作。现在的问题是,如果 @Transactional
方法中存在错误,则在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:使用弹簧4.1.7,Mybatis:3.4.4,Mybatis-spring:1.3.1
Spring Transaction和Mybatis SqlSession的方式是SqlSessionTemplate
线程安全,Spring管理,SqlSession与Spring事务管理配合使用,以确保实际使用的SqlSession是与当前Spring事务相关联的SqlSession。此外,它还管理会话生命周期,包括根据需要根据 Spring 事务配置关闭、提交或回滚会话。