1 - Configuring Transaction Manager

@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;
    }
}
  1. You create a database-specific or connection-pool specific DataSource here (MySQL is being used for this example)
  2. 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
  3. 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;
        });
    }
}

3 - Resources