MongoDB Configuration
@Configuration @EnableMongoRepositories(basePackages = "com.baeldung.repository") public class MongoConfig extends AbstractMongoClientConfiguration{ @Bean MongoTransactionManager transactionManager(MongoDatabaseFactory dbFactory) { return new MongoTransactionManager(dbFactory); } @Override protected String getDatabaseName() { return "test"; } @Override public MongoClient mongoClient() { final ConnectionString connectionString = new ConnectionString("mongodb://localhost:27017/test"); final MongoClientSettings mongoClientSettings = MongoClientSettings.builder() .applyConnectionString(connectionString) .build(); return MongoClients.create(mongoClientSettings); } }
Synchronous Transactions
@Test @Transactional public void whenPerformMongoTransaction_thenSuccess() { userRepository.save(new User("John", 30)); userRepository.save(new User("Ringo", 35)); Query query = new Query().addCriteria(Criteria.where("name").is("John")); List<User> users = mongoTemplate.find(query, User.class); assertThat(users.size(), is(1)); }
Note that we can’t use listCollections
command inside a multi-document transaction – for example:
References
https://www.baeldung.com/spring-data-mongodb-transactions