Skip to content

JPA integration

Configure LocalContainerEntityManagerFactoryBean with the same DataSource used by Kaumei JDBC. Add setJpaDialect(new HibernateJpaDialect()) so Spring knows how to access the Hibernate session. With that in place DataSourceUtils.getConnection returns the transaction-bound connection. Flush the session before executing native SQL to ensure pending entity changes reach the database.

Implement a JdbcConnectionProvider that flushes the session and exposes 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);
}
}

Inject the provider into your generated classes via the Spring configuration:

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);
}

This configuration has not been tested beyond Spring. Frameworks that expose the EntityManager and DataSource can reuse the same pattern.