有谁知道如何获取由Spring Boot创建的Hibernate SessionFactory的句柄?
你可以使用以下方法完成此操作:
SessionFactory sessionFactory = entityManagerFactory.unwrap(SessionFactory.class);
其中,entityManagerFactory是一个JPA EntityManagerFactory。
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); } }