Skip to content

Hibernate

This integration works only if you use the HibernateTransactionManager for TX management.

With the tool DataSourceUtils.getConnection we can get the current connection for the current transaction. In the Hibernate context we have to ensure to flush the session before we execute native SQL’s.

First we create a implementation of JdbcConnectionProvider which flushes the session and returns the connection.

HibernateConnectionProvider.java
public class HibernateConnectionProvider implements JdbcConnectionProvider {
private final SessionFactory sessionFactory;
private final DataSource dataSource;
public HibernateConnectionProvider(SessionFactory sessionFactory, DataSource dataSource) {
this.sessionFactory = requireNonNull(sessionFactory);
this.dataSource = requireNonNull(dataSource);
}
@Override
public Connection getConnection() {
sessionFactory.getCurrentSession().flush();
return DataSourceUtils.getConnection(dataSource);
}
}

Later we can use it in the dependency injection to be injected in our generated classes. Please find below the common code.

SpringHibernateConfig.java
@Bean
PlatformTransactionManager transactionManager(SessionFactory sessionFactory) {
return new HibernateTransactionManager(sessionFactory);
}
@Bean
JdbcConnectionProvider hibernateConnectionProvider(SessionFactory sessionFactory, DataSource dataSource) {
return new HibernateConnectionProvider(sessionFactory, dataSource);
}
@Bean
NamesService namesServiceKaumei(JdbcConnectionProvider provider) {
return new NamesServiceKaumeiJdbc(provider);
}

Not yet tested. Expected to behave similarly to Spring.