Mongo db的事务管理
网上的方式都报错 提示不能自动装配MongoDbFactory 这个接口
通过看官网学习,被我实现了
version:springboot 2.3.7
springboot mongodb 2.3.7
1
import com.mongodb.client.MongoClient;
import com.mongodb.client.MongoClients;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.mongodb.MongoDatabaseFactory;
import org.springframework.data.mongodb.MongoTransactionManager;
import org.springframework.data.mongodb.config.AbstractMongoClientConfiguration;
.
@Configuration
public class MongoConfig extends AbstractMongoClientConfiguration {
@Bean
MongoTransactionManager transactionManager(MongoDatabaseFactory dbFactory) {
return new MongoTransactionManager(dbFactory);
}
//你链接的数据库的名字
@Override
protected String getDatabaseName() {
return “”;
}
// yml中配置的mongo url 写在这里面
@Override
public @Bean
MongoClient mongoClient() {
return MongoClients.create(“mongodb://mongoadmin:XXXXXXX”);
}
}
2.在你要实现事务管理的方法上面加上
@Transactional
参考连接: https://docs.spring.io/spring-data/mongodb/docs/3.1.5/reference/html/#mongo.core
https://docs.spring.io/spring-data/mongodb/docs/3.1.5/reference/html/#mongo.mongo-java-config
https://docs.spring.io/spring-data/mongodb/docs/3.1.5/reference/html/#mongo.transactions.tx-manager