一尘不染

Spring Boot-Hibernate SessionFactory的句柄

java spring

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


阅读 317

收藏
2020-03-24

共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-03-24