Issues with Transaction Propagation in Spring Boot with Multiple Data Sources
I've been banging my head against this for hours... I'm sure I'm missing something obvious here, but I'm experiencing issues with transaction propagation when using multiple data sources in my Spring Boot application. I've set up two different data sources, one for my primary database (MySQL) and another for a secondary database (MongoDB). I am using Spring's `@Transactional` annotation, but it seems that transactions are not behaving as expected. Specifically, when I try to save data to both data sources in a single service method, the transaction for MySQL commits, but the changes in MongoDB are not reflected unless I explicitly manage the transaction. Here's a simplified version of my service method: ```java @Service public class UserService { @Autowired private UserRepository userRepository; // MySQL repo @Autowired private UserMongoRepository userMongoRepository; // MongoDB repo @Transactional public void createUser(User user) { userRepository.save(user); UserMongo userMongo = new UserMongo(user.getId(), user.getName()); userMongoRepository.save(userMongo); } } ``` However, when I run this method, I get the following stack trace: ``` org.springframework.transaction.TransactionSystemException: Could not commit; nested exception is org.springframework.dao.InvalidDataAccessApiUsageException: No transaction is currently active ``` I've tried annotating both repositories with `@Transactional` and set the propagation level to `REQUIRES_NEW`, but it seems to make no difference. My configuration for the data sources is as follows: ```java @Configuration public class DataSourceConfig { @Bean(name = "mysqlDataSource") @Primary @ConfigurationProperties("spring.datasource.mysql") public DataSource mysqlDataSource() { return DataSourceBuilder.create().build(); } @Bean(name = "mongoDataSource") @ConfigurationProperties("spring.datasource.mongo") public MongoClient mongoClient() { return MongoClients.create("mongodb://localhost:27017"); } } ``` What could be the reason for this behavior, and how can I ensure that both database operations are part of the same transaction? Are there specific configurations I need to apply when dealing with multiple data sources in Spring Boot? Any help would be greatly appreciated! For context: I'm using Java on Ubuntu. Any ideas what could be causing this? How would you solve this?