Hibernate
Spring + Hibernate
Section titled “Spring + Hibernate”Use this integration when Spring manages transactions through HibernateTransactionManager.
DataSourceUtils.getConnection yields the connection bound to the current Hibernate session.
Flush the session before running native SQL to ensure all pending changes hit the database.
Wrap the flush + connection retrieval inside a JdbcConnectionProvider bean:
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); }}Inject the provider into your generated classes through the Spring configuration:
@BeanPlatformTransactionManager transactionManager(SessionFactory sessionFactory) { return new HibernateTransactionManager(sessionFactory);}
@BeanJdbcConnectionProvider hibernateConnectionProvider(SessionFactory sessionFactory, DataSource dataSource) { return new HibernateConnectionProvider(sessionFactory, dataSource);}
@BeanNamesService namesServiceKaumei(JdbcConnectionProvider provider) { return new NamesServiceKaumeiJdbc(provider);}References
Section titled “References”Other frameworks
Section titled “Other frameworks”This approach has not been tested outside Spring. Frameworks that expose a managed Hibernate session should provide a similar provider.