Spring中使用Session出现Could not obtain transaction-synchronized Session for current thread

又是郁闷的一天,在使用Spring和Hibernate结合的时候竟然发现了这样的错误。
Could not obtain transaction-synchronized Session for current thread
在这里插入图片描述
具体的报错的代码如下,应该是这个getCurrentSession方法的问题

Query query = this.sessionFactory.getCurrentSession().createQuery("from User");

是由于getCurrentSession获取的就这一个Session,大家共用这个Session,也就因此产生了问题。
解决办法:
使用openSession代替getCurrentSession

Query query = this.sessionFactory.openSession().createQuery("from User");

或者查看是否有配置出错
1、Spring中使用Hibernate并且想要使用getCurrentSession一定要在web.xml文件中配置,一定要配置清楚,博主就是吃了这个亏了

 <!-- Spring和Hibernate使用到的过滤器 -->
  <filter>
  	<filter-name>openSessionInView</filter-name>
  	<filter-class>org.springframework.orm.hibernate5.support.OpenSessionInViewFilter</filter-class>
  </filter>
   <filter-mapping>
    <filter-name>openSessionInView</filter-name>
    <url-pattern>/*</url-pattern>
  </filter-mapping>

2、指定事务管理器

<!-- 事务 -->
	<bean id="transactionManager"
		class="org.springframework.orm.hibernate5.HibernateTransactionManager">
		<property name="sessionFactory" ref="sessionFactory" />
	</bean>
	<tx:annotation-driven transaction-manager="transactionManager" proxy-target-class="true"/>

3、这句话也尽量不要加
因为在Spring事务管理中,currentSession是绑定到SpringSessionContext中的,而不是ThreadLocalSessionContext中的,有可能会出现问题
在这里插入图片描述

<prop key="current_session_context_class">thread</prop>

那么openSession和getCurrentSession的区别有什么呢?
1、openSession,是打开Session,需要手动关闭,每次都是建立一个新的Session
2、getCurrentSession,是获取当前的这个Session,大家共用一个Session,不需要手动关闭,事务执行完成后便自动关闭

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
如果在使用自定义标识符生成器时遇到了 `Could not obtain transaction-synchronized Session for current thread` 错误,这通常是因为在生成标识符时没有正确的事务上下文。 为了解决这个问题,你可以尝试以下方法: 1. 确保你的生成器实现类上标注了 `@Singleton` 注解,确保它是单例模式的。例如: ```kotlin import io.micronaut.context.annotation.Factory import io.micronaut.context.annotation.Prototype import javax.inject.Singleton @Factory class SnowflakeIdGeneratorFactory { @Singleton @Prototype fun snowflakeIdGenerator(): SnowflakeIdGenerator { return SnowflakeIdGenerator() } } ``` 2. 在你的服务类或者控制器类使用 `@Transactional` 注解来确保你的代码在事务上下文执行。例如: ```kotlin import io.micronaut.transaction.annotation.Transactional @Transactional class YourService(private val repository: YourRepository, private val idGenerator: SnowflakeIdGenerator) { fun saveEntity(entity: YourEntity): YourEntity { val id = idGenerator.generate() entity.id = id return repository.save(entity) } } ``` 在上面的示例,我们使用 `@Transactional` 注解确保 `saveEntity` 方法在事务上下文执行。 请注意,确保你的数据库配置和事务管理器配置正确,并且你的代码在正确的事务上下文运行。如果你使用的是默认的配置,Micronaut Data 和 JPA 通常会自动处理事务。 如果问题仍然存在,请提供更多的代码和配置细节,以便我可以更具体地帮助你。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值