弹簧靴 - 手柄到休眠会话工厂
2022-08-31 14:28:22
有谁知道如何获得由Spring Boot创建的Hibernate SessionFactory的句柄?
有谁知道如何获得由Spring Boot创建的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的最简单和最不冗长的方法是:
这是带有Hibernate 4的Spring Boot 1.x的解决方案:
应用程序.属性:
spring.jpa.properties.hibernate.current_session_context_class=
org.springframework.orm.hibernate4.SpringSessionContext
配置类:
@Bean
public HibernateJpaSessionFactoryBean sessionFactory() {
return new HibernateJpaSessionFactoryBean();
}
然后,您可以像往常一样自动连接服务中的 :SessionFactory
@Autowired
private SessionFactory sessionFactory;
从带有Hibernate 5的Spring Boot 1.5开始,这是现在首选的方式:
应用程序.属性:
spring.jpa.properties.hibernate.current_session_context_class=
org.springframework.orm.hibernate5.SpringSessionContext
配置类:
@EnableAutoConfiguration
...
...
@Bean
public HibernateJpaSessionFactoryBean sessionFactory(EntityManagerFactory emf) {
HibernateJpaSessionFactoryBean fact = new HibernateJpaSessionFactoryBean();
fact.setEntityManagerFactory(emf);
return fact;
}