Spring Boot – 处理Hibernate SessionFactory

有谁知道如何获得由Spring Boot创build的Hibernate SessionFactory?

你可以用下面的方法来完成

SessionFactory sessionFactory = entityManagerFactory.unwrap(SessionFactory.class);

其中entityManagerFactory是一个JPA EntityManagerFactory

 package net.andreaskluth.hibernatesample; import javax.persistence.EntityManager; import javax.persistence.EntityManagerFactory; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.hibernate.Transaction; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; @Component public class SomeService { private SessionFactory hibernateFactory; @Autowired public SomeService(EntityManagerFactory factory) { if(factory.unwrap(SessionFactory.class) == null){ throw new NullPointerException("factory is not a hibernate factory"); } this.hibernateFactory = factory.unwrap(SessionFactory.class); } } 

自动装载你的Hibernate SessionFactory的最简单和最简单的方法是:

这是Spring Boot with Hibernate 4的解决scheme:

application.properties:

 spring.jpa.properties.hibernate.current_session_context_class= org.springframework.orm.hibernate4.SpringSessionContext 

configuration类:

 @Bean public HibernateJpaSessionFactoryBean sessionFactory() { return new HibernateJpaSessionFactoryBean(); } 

然后像往常一样在自己的服务中自动装载SessionFactory

 @Autowired private SessionFactory sessionFactory; 

从Spring Boot 1.5到Hibernate 5,现在这是首选的方法:

application.properties:

 spring.jpa.properties.hibernate.current_session_context_class= org.springframework.orm.hibernate5.SpringSessionContext 

configuration类:

 @EnableAutoConfiguration ... ... @Bean public HibernateJpaSessionFactoryBean sessionFactory(EntityManagerFactory emf) { HibernateJpaSessionFactoryBean fact = new HibernateJpaSessionFactoryBean(); fact.setEntityManagerFactory(emf); return fact; } 

伟大的工作Andreas。 我创build了一个bean版本,所以SessionFactory可以被自动assembly。

 import javax.persistence.EntityManagerFactory; import org.hibernate.SessionFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Bean; .... @Autowired private EntityManagerFactory entityManagerFactory; @Bean public SessionFactory getSessionFactory() { if (entityManagerFactory.unwrap(SessionFactory.class) == null) { throw new NullPointerException("factory is not a hibernate factory"); } return entityManagerFactory.unwrap(SessionFactory.class); } 

另一种类似于yglodt的方式

在application.properties中:

 spring.jpa.properties.hibernate.current_session_context_class=org.springframework.orm.hibernate4.SpringSessionContext 

在你的configuration类中:

 @Bean public SessionFactory sessionFactory(HibernateEntityManagerFactory hemf) { return hemf.getSessionFactory(); } 

然后像往常一样在自己的服务中自动装载SessionFactory:

 @Autowired private SessionFactory sessionFactory;