Spring Boot 2 + JPA / Hibernate 5 注入 SessionFactory 的正确姿势

pom 中整合 Spring Boot 和 JPA 处:

<parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>2.1.1.RELEASE</version>
    <relativePath/> <!-- lookup parent from repository -->
</parent>
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>

确定 Hibernate 版本:
通过查看源码,发现 Hibernate 的版本为 5.3.7。
如果@Autowired直接注入SessionFactory的话,会报错:

entityManagerFactory must not be null.

此时注入SessionFactory的正确方法:

@Autowired
private EntityManagerFactory entityManagerFactory;

public Session getSession() {
    return entityManagerFactory.unwrap(SessionFactory.class).openSession();
}

版权声明:本文为qq_15329947原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。