如何在Spring启动时自动装配Hibernate SessionFactory

Ich*_*aki 8 spring hibernate spring-boot

我已经创建了一个spring启动应用程序,我想处理Hibernate SessionFactory,所以在我的服务类中,我可以像下面这样调用Hibernate SessionFactory:

@Autowired
private SessionFactory sessionFactory;
Run Code Online (Sandbox Code Playgroud)

我在stackoverflow中发现了一个类似的问题,我必须在application.properties中添加以下行:

spring.jpa.properties.hibernate.current_session_context_class=org.springframework.orm.hibernate4.SpringSessionContext
Run Code Online (Sandbox Code Playgroud)

但我收到这个错误:

Cannot resolve property 'current_session_context_class' in java.lang.String
Run Code Online (Sandbox Code Playgroud)

我怎么解决这个问题?

pom.xml依赖项:

<dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-jpa</artifactId>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
        </dependency>
    </dependencies>
Run Code Online (Sandbox Code Playgroud)

Kar*_*del 13

从2.0版开始,JPA提供了对底层实现的API的轻松访问.的EntityManagerEntityManagerFactory提供unwrap返回JPA实现的相应的类的方法.

在Hibernate的情况下,这些是SessionSessionFactory.

SessionFactory sessionFactory = entityManagerFactory.unwrap(SessionFactory.class);
Run Code Online (Sandbox Code Playgroud)

  • 您的解决方案将抛出:java.lang.NullPointerException:null.必须在需要时调用entityManagerFactory.unwrap(SessionFactory.class).我也习惯了旧的事务管理器,我不得不改变经典的sessionFactory.getCurrentTransaction(); 到sessionFactory.openTransaction(); 我真的希望它不会忽略Spring管理的事务. (2认同)

Bar*_*ler 5

尝试HibernateJpaSessionFactoryBean在您的 Spring 配置中启用。

@Bean
public HibernateJpaSessionFactoryBean sessionFactory() {
    return new HibernateJpaSessionFactoryBean();
}
Run Code Online (Sandbox Code Playgroud)

看看:https : //stackoverflow.com/a/33881946/676731

通过 Spring 配置,我的意思是用@Configurationannotation 或@SpringBootApplication(它隐式地用 注释@Configuration)注释的类。