原文:https://www.cnblogs.com/vettel0329/p/10778931.html
依赖:
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-mongodb</artifactId> </dependency>
创建配置类,开启事务
@Configuration public class TransactionConfig { @Bean MongoTransactionManager transactionManager(MongoDbFactory factory){ return new MongoTransactionManager(factory); } }
开启事务:
@Service public class UserService { @Resource MongoTemplate mongotemplate; public List<User> getAllUser(){ return mongotemplate.findAll(User.class); } @Transactional public boolean addUser(User user, UserInfo userInfo){ user.setUserInfo(userInfo); mongotemplate.save(userInfo); // int a = 1/0; //事务测试代码 mongotemplate.save(user); return true; } }
注:以上为MongoTemplate方式,MongoTemplate和MongoRepository方式都与Spring整合SpringDataMongoDB相同