Spring Boot 1.5.x(含1.5.10)集成Hibernate 5的SessionFactory配置方案
Hey there, let's work through this common issue where your Spring Boot 1.5.x app can't locate the org.hibernate.SessionFactory bean. Since HibernateJpaSessionFactoryBean is marked as deprecated, we'll follow the official guidance from its Javadoc to set things up the right way.
Step 1: Understand the Deprecation Context
First, let's reference the key note from the HibernateJpaSessionFactoryBean Javadoc:
As of Spring 4.3, in favor of
EntityManagerFactory.unwrap(SessionFactory.class)
This tells us we should stop relying on the deprecated bean and instead extract the SessionFactory directly from the auto-configured EntityManagerFactory.
Step 2: Create a Configuration Bean for SessionFactory
Add this configuration class to your project. It will expose a SessionFactory bean by unwrapping it from Spring's auto-provided EntityManagerFactory:
import org.hibernate.SessionFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import javax.persistence.EntityManagerFactory; @Configuration public class HibernateSessionConfig { @Autowired private EntityManagerFactory entityManagerFactory; @Bean public SessionFactory sessionFactory() { // Unwrap the JPA EntityManagerFactory to access the underlying Hibernate SessionFactory return entityManagerFactory.unwrap(SessionFactory.class); } }
Step 3: Inject and Use SessionFactory
Now you can inject the SessionFactory into any component (service, repository, etc.) just like any other Spring-managed bean:
import org.hibernate.SessionFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; @Service public class YourBusinessService { private final SessionFactory sessionFactory; @Autowired public YourBusinessService(SessionFactory sessionFactory) { this.sessionFactory = sessionFactory; } public void performHibernateOperation() { try (var session = sessionFactory.openSession()) { // Add your Hibernate-specific logic here (e.g., querying, saving entities) } } }
Why This Works
Spring Boot auto-configures an EntityManagerFactory for JPA out of the box. Since we're using Hibernate as the JPA provider, this EntityManagerFactory wraps a native Hibernate SessionFactory. The unwrap() method safely gives us access to that underlying SessionFactory, which is the recommended approach now that the old bean is deprecated.
内容的提问来源于stack exchange,提问作者Manuel Jordan

