springboot(Spring5) + hibernate

  • 1、Spring5的坑:Could not obtain transaction-synchronized Session for current thread
  • 2、spring boot + jpa报错:No CurrentSessionContext configured

https://blog.csdn.net/RL_LEEE/article/details/84321282
https://blog.csdn.net/qq_37769323/article/details/104054581

错误提示很直白了,就是当前没有事务的session,所以报错, 将代码做以下调整,可以解决:

Session session = null;
try {
	    session = currentSession();
	} catch (HibernateException he) {
		//当前没有事务不做任何处理
	}

Spring3在没有当前事务的情况下不会报错,Spring5却出现了错误?追踪下源码,发现两者的区别。

logger.debug("Opening Hibernate Session");
Session session = (entityInterceptor != null ?
sessionFactory.openSession(entityInterceptor) : sessionFactory.openSession());
在没有获取到当前事务的session时创建一个session,所以不管当前有没有做事务(注解或显示创建),getSession()都不会报错。

再看Spring5,从HibernateDaoSupport开始跟踪currentSession()的实现,如果你的SessionFactory配置的是LocalSessionFactoryBean的工厂模式的话,会在org.hibernate.internal.SessionFactoryImpl找到CurrentSession的实现

	public Session getCurrentSession() throws HibernateException {
		if ( currentSessionContext == null ) {
			throw new HibernateException( "No CurrentSessionContext configured!" );
		}
		return currentSessionContext.currentSession();
	}
spring.jpa.properties.hibernate.current_session_context_class=org.springframework.orm.hibernate5.SpringSessionContext
posted @ 2021-11-17 09:14  沉梦匠心  阅读(536)  评论(0编辑  收藏  举报