小编典典

Spring Boot-休眠会话工厂的句柄

spring-boot

有谁知道如何获取由Spring Boot创建的Hibernate SessionFactory的句柄?


阅读 463

收藏
2020-05-30

共1个答案

小编典典

您可以使用以下方法完成此操作:

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);
  }

}
2020-05-30