先来一张图,如果不是你遇到的问题,请出门左转,如果正好是你遇到问题,救活人参果树的方子找到了

aa.jpg
请继续往下看
未使用SpringBoot+JPA的时候你注入SessionFactory的方式可能是这样的
@Resource(name = "sessionFactory")
private SessionFactory sessionFactory;
protected Session getSession() {
return sessionFactory.getCurrentSession();
}
使用SpringBoot+JPA的时候正确注入SessionFactory姿势
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.1.5.RELEASE</version>
<relativePath/>
</parent>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
@Autowired
private EntityManagerFactory entityManagerFactory;
protected Session getSession() {
return entityManagerFactory.unwrap(SessionFactory.class).openSession();
}
打完收工,诶,等等,你以为这样就完了?这样的话,在数据通过update()进行更新的时候会出现一个大坑
先告诉你坑在哪里:执行update()操作数据并没有更新,怎么避免这个问题呢
使用 getCurrentSession() 替换 openSession()
openSession() 与 getCurrentSession()的区别
openSession :是创建一个新的session对象,而且每次使用都会创建一个新的session,如果连续调用该方法,则获得的session不是同一个对象,并且使用完需要调用close方法关闭session。
getCurrentSession :是获取当前上下文一个session对象,当第一次使用此方法时,会自动产生一个session对象,并且连续使用多次时,得到的session都是同一个对象,简单而言,getCurrentSession 就是:如果有已经使用的,用旧的,如果没有,建新的。
在实际开发中,往往使用getCurrentSession多,因为一般是处理同一个事务(即是使用一个数据库的情况),所以在一般情况下比较少使用openSession或者说openSession是比较老旧的一套接口了;
getCurrentSession 来说,有以下一些特点:
1.用途,界定事务边界
2.事务提交会自动close,不需要像openSession一样自己调用close方法关闭session
那好吧,既然说了 使用 getCurrentSession() 替换 openSession() 那就跑起来吧,哗啦一下又掉坑里了

b.jpg
我擦: org.hibernate.HibernateException: No CurrentSessionContext configured!
网上一查,说是需要在application.properties 配置
spring.jpa.properties.hibernate.current_session_context_class = org.springframework.orm.hibernate5.SpringSessionContext
配置好之后操练起来,哗啦一下又掉坑里了,还好你身边没有狗,要不然非被你日了

cc.jpg
这怎么搞,怎么搞?
说说正确的 Spring Boot JPA + Hibernate 注入 SessionFactory 的正确姿势吧
@PersistenceContext
protected EntityManager entityManager;
protected Session getSession() {
return entityManager.unwrap(Session.class);
}
这才是注入SessionFactory的正确姿势,亲测有效
这时候你肯定要掀桌子骂娘了,费了这么半天劲儿你早告诉我不就行了么?
一入深坑才知道深似海,你不入深坑不知道坑有多深
想不想联系到我?想?不想?到底想不想?想,想我就把我的QQ群:578060039 告诉你
打完收工
网友评论