简体   繁体   English

如何使Mybatis需要交易?

[英]How can I make mybatis require a transaction?

In my project I am using Spring and mybatis, with mybatis-spring gluing them together. 在我的项目中,我使用的是Spring和mybatis,而mybatis-spring将它们粘合在一起。 I am using Spring's declarative @Transactional annotations around my service layers, which call to the mybatis mappers. 我在服务层周围使用Spring的声明性@Transactional批注,该批注调用了mybatis映射器。

I would prefer that NONE of my mapper methods can be called without an active transaction. 我希望没有活动事务就可以调用我的映射器方法中的任何一个。 Instead, they quietly run in a transactionless context (or else they are starting a new transaction). 相反,它们在无事务的上下文中安静地运行(否则,它们将开始新的事务)。

Is there a way to disable this behavior and make it act more like a MANDATORY propagation level? 有没有办法禁用此行为,并使它的行为更像是强制传播级别?

The easiest way to do that is to create custom TransactionFactory which will check if there is active transaction and throw exception otherwise. 最简单的方法是创建自定义TransactionFactory ,它将检查是否存在活动事务,否则将引发异常。

class MandatoryTransactionSpringManagedTransactionFactory extends SpringManagedTransactionFactory {
     public Transaction newTransaction(DataSource dataSource, TransactionIsolationLevel level, boolean autoCommit) {
         if (!TransactionSynchronizationManager.isActualTransactionActive()) {
              throw new IllegalTransactionStateException(
                "No existing transaction found during mapper invocation");
         }
         return super.newTransaction(dataSource);

} } }}

It should be used to configure org.mybatis.spring.SqlSessionFactoryBean 它应该用于配置org.mybatis.spring.SqlSessionFactoryBean

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM