You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

基于Spring Boot、Spring MVC和Hibernate的Twitter仿品项目技术问题求助

关于Spring Boot+Hibernate中Session获取与事务整合的问题排查与解决

嘿,我完全理解卡了两天的那种挫败感——咱们先从你贴的BaseDaoImpl代码说起,这里其实藏着几个容易踩的坑:

@Autowired 
private EntityManagerFactory entityManagerFactory; 

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

问题根源分析

每次调用getSession()都会新建一个EntityManager实例,而Spring的@Transactional注解管理的是另一个由Spring容器创建、绑定到当前线程的EntityManager。这就导致你的DAO层用的Session和Service层事务上下文完全脱节:

  • 事务注解根本管不到你手动创建的Session,所以会出现事务不生效、数据回滚失败的情况
  • 频繁创建EntityManager还会带来不必要的资源开销,甚至可能引发连接池耗尽的问题

正确的Session获取方式

推荐两种更贴合Spring生态的方案:

方案1:直接注入EntityManager,再unwrap成Session

Spring会自动把当前事务绑定的EntityManager注入进来,完全不用你手动创建:

@Autowired
private EntityManager entityManager;

public Session getSession() {
    return entityManager.unwrap(Session.class);
}

方案2:用Hibernate的SessionFactory直接注入

如果你的项目更偏向原生Hibernate用法,可以直接注入SessionFactory:

@Autowired
private SessionFactory sessionFactory;

public Session getSession() {
    return sessionFactory.getCurrentSession();
}

这里的getCurrentSession()会自动获取当前事务上下文绑定的Session,完美适配Spring的@Transactional管理

额外注意事项

  • 确保你的Service类上的@Transactional注解是Spring的org.springframework.transaction.annotation.Transactional,而不是JTA或者其他框架的
  • 检查Spring Boot配置文件里是否开启了事务自动配置(默认是开启的,但如果手动关闭了要重新打开)
  • 如果是在测试环境,记得用@Transactional或者@Rollback来管理测试事务

这样调整后,你的Session就能和Service层的事务完全联动起来,之前的问题应该就能解决啦!

内容的提问来源于stack exchange,提问作者Shelton

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.27 04:01:59