Spring Boot 2.5整合Hibernate 5调用getSession返回null问题求助
Spring Boot 2.5 + Hibernate 5 获取Session返回null解决方案
核心原因
Spring Boot 2.2及以上版本对Hibernate的EntityManager做了代理封装,旧版本直接unwrap Session的方式不再兼容,手动配置current_session_context_class反而会覆盖Spring Boot自动生成的事务绑定规则,导致Session和事务上下文解绑。
操作步骤
第一步:删除冗余配置
删掉你当前application配置里的这行:
spring.jpa.properties.hibernate.current_session_context_class=org.springframework.orm.hibernate5.SpringSessionContext
Spring Boot 2.5集成Hibernate 5时会自动配置该会话上下文,手动指定会破坏默认的事务绑定逻辑。
第二步:调整Session获取逻辑
推荐通过SessionFactory拿当前绑定事务的Session,兼容性更高,调整你的代码如下:
import org.hibernate.Session; import org.hibernate.SessionFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Repository; import org.springframework.transaction.annotation.Transactional; import javax.persistence.EntityManager; @Repository @Transactional public class ABC{ @Autowired private EntityManager entityManager; private Session getSession() { // 先从EntityManager获取SessionFactory,再拿当前事务绑定的Session SessionFactory sessionFactory = entityManager.getEntityManagerFactory().unwrap(SessionFactory.class); return sessionFactory.getCurrentSession(); } public String gettingSession() { Session session = getSession(); // 你的业务查询逻辑 // List<EMP> employee = (List<EMP>) session.createQuery("from EMP", EMP.class).list(); return "hello"; } }
第三步:检查必要配置和生效条件
- 确认
@Transactional注解使用的是org.springframework.transaction.annotation.Transactional,不是javax.transaction包下的同名注解 - 确认ABC类在启动类的包扫描路径下,不要手动new ABC类的实例调用方法,必须通过Spring注入的实例调用才能触发事务和EntityManager的注入
- 确保实体类EMP添加了
@Entity注解,启动类添加了@EntityScan注解扫描到EMP所在的包 - application配置中添加对应数据库的方言配置,示例(MySQL 8为例):
spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.MySQL8Dialect
以上配置完成后即可正常拿到Session实例。
内容的提问来源于stack exchange,提问作者Imperial
相关产品推荐
相关产品推荐

