Skip to content

JPA integration

With the tool DataSourceUtils.getConnection we can get the current connection for the current transaction. this will only work, if the LocalContainerEntityManagerFactoryBean is aware of the used Datasource and if we set the correct setJpaDialect(new HibernateJpaDialect()).

In the JPA/Hibernate context we have to ensure to flush the session before we execute native SQL’s.

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

JpaConnectionProvider.java
public class JpaConnectionProvider implements JdbcConnectionProvider {
private final EntityManager entityManager;
private final DataSource dataSource;
public JpaConnectionProvider(EntityManager entityManager, DataSource dataSource) {
var jpaDialect = entityManager.getEntityManagerFactory() instanceof EntityManagerFactoryInfo info
? info.getJpaDialect()
: null;
if (jpaDialect == null) {
throw new IllegalArgumentException("JPA Dialect not found");
} else if (jpaDialect instanceof HibernateJpaDialect) {
this.entityManager = entityManager;
this.dataSource = requireNonNull(dataSource);
} else {
throw new IllegalArgumentException("Not supported JPA Dialect: " + jpaDialect.getClass().getCanonicalName());
}
}
@Override
public Connection getConnection() {
entityManager.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.

SpringJpaConfig.java
@Bean
AbstractEntityManagerFactoryBean entityManagerFactory(DataSource dataSource) {
LocalContainerEntityManagerFactoryBean em = new LocalContainerEntityManagerFactoryBean();
em.setJpaDialect(new HibernateJpaDialect());
em.setDataSource(dataSource);
em.setPersistenceProvider(new HibernatePersistenceProvider());
return em;
}
@Bean
PlatformTransactionManager jpaTransactionManager(EntityManagerFactory entityManagerFactory, DataSource dataSource) {
var transactionManager = new JpaTransactionManager(entityManagerFactory);
transactionManager.setDataSource(dataSource);
return transactionManager;
}
@Bean
JdbcConnectionProvider jpaConnectionProvider(EntityManager entityManager, DataSource dataSource) {
return new JpaConnectionProvider(entityManager, dataSource);
}
@Bean
NamesService customerServiceKaumei(JdbcConnectionProvider provider) {
return new NamesServiceKaumeiJdbc(provider);
}

We have a simple test

Not yet tested. Expected to behave similarly to Spring.