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 openSession() {
   return entityManagerFactory.unwrap(SessionFactory.class).openSession();
}

说明:

需要引入EntityManagerFactory而不是seesionFactory。hibernate4之后的版本,然后正常用就可以啦.....

 

 

打开wx扫一扫领取惊喜:

                                                                                                                        我是一条随风飘摇的结尾符~~~

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 3
    评论
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值