java - 在 Spring Boot 2.0/Hibernate 5 中获取 SessionFactory

标签 java spring hibernate spring-boot

我在 Spring Boot 1.5.x 中使用 HibernateJpaSessionFactoryBean 来为我的 session 获取 session 工厂 bean。由于现在已弃用,我尝试通过在 EntityManagerFactory 中展开来使用 session 工厂。但是,我无法让 EntityManagerFactory Autowiring 。没有 bean 定义它。

我需要做什么来连接 EntityManagerFactory? entityManagerFactory 保持为空。

/**
 * A class to hold necessary data access beans.
 */
@Configuration
@EnableTransactionManagement
public class DataBeans {

    @Autowired
    private EntityManagerFactory entityManagerFactory;

    /**
     * This bean needs to be wired in so that a SessionFactory can be wired in to other data access beans.
     *
     * @return a session factory bean
     */
    @Bean
    public SessionFactory sessionFactoryProvider() {
        return entityManagerFactory.unwrap(SessionFactory.class);
    }
}



@SpringBootApplication
public class AppBootMain {
    public static void main(String[] args) {
        SpringApplication.run(AppBootMain.class, args);
    }
}

应用程序属性:

spring.datasource.driverClassName=org.hsqldb.jdbc.JDBCDriver
spring.datasource.url=jdbc:hsqldb:mem:student_db
spring.datasource.username=sa
spring.datasource.password=

spring.jpa.database-platform=org.hibernate.dialect.HSQLDialect
spring.jpa.show-sql=false
spring.jpa.hibernate.ddl-auto=create-drop

# this ensures that a session factory bean is available
spring.jpa.properties.hibernate.current_session_context_class=org.springframework.orm.hibernate5.SpringSessionContext

注意:我尝试更改 current_session_context_class 以在包中指定 hibernate5,但没有成功。

运行 bootRun 时出错: ````

org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'dataBeans': Unsatisfied dependency expressed through field 'entityManagerFactory'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'sessionFactoryProvider' defined in class path resource [org/webapp/example/school/data/repository/DataBeans.class]: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.hibernate.SessionFactory]: Circular reference involving containing bean 'dataBeans' - consider declaring the factory method as static for independence from its containing instance. Factory method 'sessionFactoryProvider' threw exception; nested exception is java.lang.NullPointerException
    at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:587)
    at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:91)
    at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:373)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1348)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:578)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:501)
    at org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:317)
    at org.springframework.beans.factory.support.AbstractBeanFactory$$Lambda$94/681094281.getObject(Unknown Source)
    at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:228)
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:315)
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:199)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:760)
    at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:869)
    at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:550)
    at org.springframework.boot.web.servlet.context.ServletWebServerApplicationContext.refresh(ServletWebServerApplicationContext.java:140)
    at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:759)
    at org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:395)
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:327)
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:1255)
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:1243)
    at org.webapp.example.school.AppBootMain.main(AppBootMain.java:27)
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'sessionFactoryProvider' defined in class path resource [org/webapp/example/school/data/repository/DataBeans.class]: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.hibernate.SessionFactory]: Circular reference involving containing bean 'dataBeans' - consider declaring the factory method as static for independence from its containing instance. Factory method 'sessionFactoryProvider' threw exception; nested exception is java.lang.NullPointerException
    at org.springframework.beans.factory.support.ConstructorResolver.instantiateUsingFactoryMethod(ConstructorResolver.java:587)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateUsingFactoryMethod(AbstractAutowireCapableBeanFactory.java:1254)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:1103)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:541)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:501)
    at org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:317)
    at org.springframework.beans.factory.support.AbstractBeanFactory$$Lambda$94/681094281.getObject(Unknown Source)
    at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:228)
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:315)
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:199)
    at org.springframework.beans.factory.config.DependencyDescriptor.resolveCandidate(DependencyDescriptor.java:251)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:1138)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:1065)
    at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:584)
    ... 20 common frames omitted
Caused by: org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.hibernate.SessionFactory]: Circular reference involving containing bean 'dataBeans' - consider declaring the factory method as static for independence from its containing instance. Factory method 'sessionFactoryProvider' threw exception; nested exception is java.lang.NullPointerException
    at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:185)
    at org.springframework.beans.factory.support.ConstructorResolver.instantiateUsingFactoryMethod(ConstructorResolver.java:579)
    ... 33 common frames omitted
Caused by: java.lang.NullPointerException: null
    at org.webapp.example.school.data.repository.DataBeans.sessionFactoryProvider(DataBeans.java:30)
    at org.webapp.example.school.data.repository.DataBeans$$EnhancerBySpringCGLIB$$ebde0844.CGLIB$sessionFactoryProvider$0(<generated>)
    at org.webapp.example.school.data.repository.DataBeans$$EnhancerBySpringCGLIB$$ebde0844$$FastClassBySpringCGLIB$$f2417c25.invoke(<generated>)
    at org.springframework.cglib.proxy.MethodProxy.invokeSuper(MethodProxy.java:228)
    at org.springframework.context.annotation.ConfigurationClassEnhancer$BeanMethodInterceptor.intercept(ConfigurationClassEnhancer.java:361)
    at org.webapp.example.school.data.repository.DataBeans$$EnhancerBySpringCGLIB$$ebde0844.sessionFactoryProvider(<generated>)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:483)
    at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:154)
    ... 34 common frames omitted

> Task :bootRun FAILED

我尝试将 EntityManagerFactory 作为创建 session 工厂的 bean 方法的参数,但由于循环依赖而失败。

    @Bean
public SessionFactory sessionFactoryProvider(EntityManagerFactory entityManagerFactory) {
    return entityManagerFactory.unwrap(SessionFactory.class);
}

最佳答案

从1.5升级到2.1.3时,我遇到了同样的问题,并通过在Dao类中获取Session/SessionFactory而不是在spring init时 Autowiring 来解决。

下面是一个例子:

  1. 删除示例中的 DataBean
  2. 在 Dao 类中使用以下方法获取 session :
@Repository
@Transactional
public class XXXDao {
    @Autowired
    private EntityManager entityManager;

    private Session getSession() {
        return entityManager.unwrap(Session.class);
    }
...
}

如果您确实需要 SessionFactory,请使用以下编码,并注意您可能需要手动处理事务。

@Repository
public class XXXDao {

    @Autowired
    private EntityManagerFactory entityManagerFactory;

    private SessionFactory getSessionFactory() {
        return entityManagerFactory.unwrap(SessionFactory.class);
    }
...
}

我建议您也检查一下 Spring boot hibernate no transaction is in progress对于交易问题

关于java - 在 Spring Boot 2.0/Hibernate 5 中获取 SessionFactory,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50317045/

相关文章:

java - Jackson 解析中对象值为 null

java - CrudRepository 保存方法不返回更新后的实体

java - 当我的 JFrame 恢复(取消图标)时,如何重新绘制内容?

java - 查找并删除eclipse java中的所有getter方法

java - 我在使用 JAXB 时不需要 package-info.java?

spring-cloud-starter-config POST/env 不工作

java - @Value 不从 application.properties 注入(inject)数据

java - Struts 表单为空

java - jpa删除错误,同时打印更新sql

java - JPA hibernate : Invalid persistence. xml