Search code examples
javapostgresqlspring-boottransactionaljdbi

How to integrate Spring transaction management with JDBI 3?


I am trying to integrate spring transaction management with JDBI 3. When i implement below solution, with auto-commit property is set to false, i get below exception* due to closing handles before committing or rolling back transactions.

On the other hand, if auto-commit property set to true there is not any transaction error but this time rollback does not work (after runtime exception) and so X object is being persisted to database.

I use spring 2.0.3, JDBI 3.0.0-beta2 .

Is there any recommended/applicable solution for that?

Below is config class:

@Bean
public HikariDataSource hikariDataSource() {
    HikariConfig dataSourceConfig = new HikariConfig();
    dataSourceConfig.setDriverClassName(driverClassName);
    dataSourceConfig.setJdbcUrl(jdbcUrl);
    dataSourceConfig.setUsername(username);
    dataSourceConfig.setPassword(password);
    dataSourceConfig.setAutoCommit(true);
    return new HikariDataSource(dataSourceConfig);
}

@Bean
public TransactionAwareDataSourceProxy transactionAwareDataSourceProxy(HikariDataSource dataSource) {
    return new TransactionAwareDataSourceProxy(dataSource);
}

@Bean
public PlatformTransactionManager platformTransactionManager(HikariDataSource dataSource) {
    return new DataSourceTransactionManager(dataSource);
}

@Bean
public Jdbi jdbi(TransactionAwareDataSourceProxy transactionAwareDataSourceProxy) {
    Jdbi jdbi = Jdbi.create(transactionAwareDataSourceProxy);
    jdbi.installPlugin(new SqlObjectPlugin());
    return jdbi;
}

Here is service layer

@Override
@Transactional
public Long createX(X x) {
    Long aLong = xDao.insertX(x);
    if(true) throw new RuntimeException();
    return aLong;
}

*Improper transaction handling detected: A Handle with an open transaction was closed. Transactions must be explicitly committed or rolled back before closing the Handle. Jdbi has rolled back this transaction automatically.


Solution

  • Problem solved. I was using older version of JDBI, updated it (check this thread ) and everything resolved.