SpringBoot2 + Hibernate5注入SessionFactory的正确方法

pom中整合SpringBoot和Hibernate处:
确定springboot版本:

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

确定hibernate版本:
通过查看源码,发现hibernate的版本为5.3.7。

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-jpa</artifactId>
        </dependency>

如果@Autowired直接注入SessionFactory的话,会报错:

entityManagerFactory must not be null.

此时注入SessionFactory的正确方法:

    @Autowired
    private EntityManagerFactory entityManagerFactory;

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

猜你喜欢

转载自blog.csdn.net/qq_15329947/article/details/85232287
今日推荐