简体   繁体   中英

Java Spring: Compatibility for both transactional and non-transactional versions of mongodb

I'm using Spring Boot 2.1.2 release (mongodb-driver v 3.8.2) and developing web application that operates with mongodb. My application is compatible with mongodb 3.4 version (This version doesn't support transactions) and now I'm introducing transactional mechanism. I annotate my service method with transactional annotation

@Transactional
    public void process(Object argument) {
        ...
        ...
        ...
    }

and it works fine for mongodb v 4, everything works just excpected - failed transactions are rolledback.

But when I start my app with mongodb v 3.4 my app crashes with

Sessions are not supported by the MongoDB cluster to which this client is connected

exception.

The problem is that I want my app to support both cases: transactional and non-transactional with the same code (for both mongodb versions). So I wonder how can I do it? It seems like my application should create session only for specific version of mongo, ie this annotation should be processed only for this case.

How can I do it?

I have found a solution. Spring checks for existence of PlatformTransactionManager in current context before creating a transaction. So if this bean is not defined, then session wouldn't be opened for transaction. Thus I had used on condition bean for this purpose in my configuration class:

    @Bean
    @Autowired
    @ConditionalOnExpression("'${mongo.transactions}'=='enabled'")
    MongoTransactionManager mongoTransactionManager(MongoDbFactory dbFactory) {
        return new MongoTransactionManager(dbFactory);
    }

So MongoTransactionManager bean will be created only if mongo.transactions parameter is set to enabled.

不确定它是否有效,但是您可以尝试将@EnableTransactionManagement批注移动到新的配置类,将批注@Configuration@Profile("enableTransactions")到配置类,并在给定配置文件时运行应用程序需要自动配置事务管理,例如使用:

mvn spring-boot:run -Dspring-boot.run.profiles=enableTransactions

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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