JPA integration
Spring/JPA with Hibernate
Section titled “Spring/JPA with Hibernate”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.
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.
@BeanAbstractEntityManagerFactoryBean entityManagerFactory(DataSource dataSource) { LocalContainerEntityManagerFactoryBean em = new LocalContainerEntityManagerFactoryBean(); em.setJpaDialect(new HibernateJpaDialect()); em.setDataSource(dataSource); em.setPersistenceProvider(new HibernatePersistenceProvider()); return em;}
@BeanPlatformTransactionManager jpaTransactionManager(EntityManagerFactory entityManagerFactory, DataSource dataSource) { var transactionManager = new JpaTransactionManager(entityManagerFactory); transactionManager.setDataSource(dataSource); return transactionManager;}
@BeanJdbcConnectionProvider jpaConnectionProvider(EntityManager entityManager, DataSource dataSource) { return new JpaConnectionProvider(entityManager, dataSource);}
@BeanNamesService customerServiceKaumei(JdbcConnectionProvider provider) { return new NamesServiceKaumeiJdbc(provider);}We have a simple test
References
Section titled “References”Other frameworks
Section titled “Other frameworks”Not yet tested. Expected to behave similarly to Spring.