@Configuration
@EnableTransactionManagement
public class MySpringConfig {
@Bean
public DataSource dataSource() {
return new MysqlDataSource(); // (1)
}
@Bean
public PlatformTransactionManager transactionManager() {
return new DataSourceTransactionManager(dataSource()); // (2)
}
@Bean
public TransactionTemplate transactionTemplate() {
TransactionTemplate transactionTemplate new TransactionTemplate(transactionManager()); // (3)
// the transaction settings can be set here explicitly if so desired
transactionTemplate.setIsolationLevel(TransactionDefinition.ISOLATION_READ_UNCOMMITTED);
transactionTemplate.setTimeout(30); // 30 seconds
// and so forth...
return transactionTemplate;
}
}
You create a TransactionManager, which needs a DataSource to be able to manage transactions. For other integrations or a more in-depth understanding, it helps to have a quick look at all possible PlatformTransactionManager implementations that Spring offers
You create a TransactionTemplate to
2 - Using TransactionTemplate
@Service
public class UserService {
@Autowired
private TransactionTemplate template;
public Long registerUser(User user) {
Long id = template.execute(status -> {
// execute some SQL that e.g.
// inserts the user into the db and returns the autogenerated id
return id;
});
}
}