Spring Boot - Hibernate SessionFactory 的句柄 [英] Spring Boot - Handle to Hibernate SessionFactory

查看:38
本文介绍了Spring Boot - Hibernate SessionFactory 的句柄的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Does anyone know how to get a handle the Hibernate SessionFactory that is created by Spring Boot?

推荐答案

您可以通过以下方式实现:

You can accomplish this with:

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

其中 entityManagerFactory 是 JPA EntityManagerFactory.

where entityManagerFactory is an 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);
  }

}

这篇关于Spring Boot - Hibernate SessionFactory 的句柄的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆