架个spring4+hibernate4的demo,dao层直接注入的sessionFactory,然后用getCurrentSession方法获取session,然后问题来了,直接报错:

Could not obtain transaction-synchronized Session for current thread

提示无法获取当前线程的事务同步session,略微奇怪,这和事务有什么关系..然后百度一下有人说改成用openSession方法就好了,那我又百度了一下这2个方法的区别:

(1)openSession每次打开都是新的Session,所以多次获取的Session实例是不同的,并且需要人为的调用close方法进行Session关闭。
(2)getCurrentSession是从当前上下文中获取Session并且会绑定到当前线程,第一次调用时会创建一个Session实例,如果该Session未关闭,后续多次获取的是同一个Session实例;事务提交或者回滚时会自动关闭Sesison,无需人工关闭。

看起来这个getCurrentSession方法的确和事务有点关系.然后我加上事务:

    <bean id="transactionManager"
class="org.springframework.orm.hibernate4.HibernateTransactionManager">
<property name="sessionFactory">
<ref bean="sessionFactory" />
</property>
</bean> <tx:annotation-driven transaction-manager="transactionManager"/>

然后在dao层加上@Transaction注解,再运行ok了..不过好奇驱使吧,看了一下getCurrentSession的源码(我的demo中用的spring的实现类),关键点:

if (TransactionSynchronizationManager.isSynchronizationActive()) {
Session session = this.sessionFactory.openSession();
if (TransactionSynchronizationManager.isCurrentTransactionReadOnly()) {
session.setFlushMode(FlushMode.MANUAL);
}
SessionHolder sessionHolder = new SessionHolder(session);
TransactionSynchronizationManager.registerSynchronization(
new SpringSessionSynchronization(sessionHolder, this.sessionFactory, true));
TransactionSynchronizationManager.bindResource(this.sessionFactory, sessionHolder);
sessionHolder.setSynchronizedWithTransaction(true);
return session;
}
else {
throw new HibernateException("Could not obtain transaction-synchronized Session for current thread");
}

然后点进去看了一下isSynchronizationActive()方法:

public static boolean isSynchronizationActive() {
return (synchronizations.get() != null);
}

get方法说明:

Returns the value in the current thread's copy of this thread-local variable. If the variable has no value for the current thread, it is first initialized to the value returned by an invocation of the initialValue method.

然后再看initialValue的说明:

This implementation simply returns null; if the programmer desires thread-local variables to have an initial value other than null, ThreadLocal must be subclassed, and this method overridden. Typically, an anonymous inner class will be used.

到此问题明了了,补充一点之前配置文件中配了事务,不过是原来那种在配置中根据方法名字来定义事务传播的方式,但是在dao中并没有继承它,故实际上是没有事务的,只有实现.而在spring的事务实现中需要判断当前线程中的事务是否同步,而没有事务的时候,那个判断是否同步的方法会因为get返回初始的null值而返回false,最终导致throw一个Could not obtain transaction-synchronized Session for current thread的异常.

综上:spring4+hibernate4,使用hibernate的api的时候需要配置事务的,如果不配置事务会导致获取当前session抛出异常.

Hibernate4中使用getCurrentSession报Could not obtain transaction-synchronized Session for current thread的更多相关文章

  1. Could not obtain transaction-synchronized Session for current thread原因及解决方案

            在开发中,碰到到了Could not obtain transaction-synchronized Session for current thread异常,因此特意记录下. 一.问 ...

  2. 关于Could not obtain transaction-synchronized Session for current thread 这个异常。

    Could not obtain transaction-synchronized Session for current thread 这个异常之前非常让我头大.对于网上的各种说法都试了一下反正都不 ...

  3. org.hibernate.HibernateException: Could not obtain transaction-synchronized Session for current thread

    spring与hibernate整合报错 org.hibernate.HibernateException: Could not obtain transaction-synchronized Ses ...

  4. 关于Hibernate Could not obtain transaction-synchronized Session for current thread

    转载自 http://blog.csdn.net/flyjiangs/article/details/51537381 最近几年一直再搞android,最近闲下来了,顺便玩一下web. 整了个最新版本 ...

  5. 记一次bug思考过程:HibernateException: Could not obtain transaction-synchronized Session for current thread

    场景:把从客户端提交的任务放到线程池执行 异常:HibernateException: Could not obtain transaction-synchronized Session for cu ...

  6. Hibernate Could not obtain transaction-synchronized Session for current thread问题处理

    项目通过Hibernate查询时报出如下错误: Hibernate Could not obtain transaction-synchronized Session for current thre ...

  7. 报错解决:No Hibernate Session bound to thread, and configuration does not allow creation of non-transactional one here

    大概分析一般使用了注解才会报这方面的错 1.没有在spring的ApplicationContext.xml中开启注解事务 <!-- 开启注解事务 --> <tx:annotatio ...

  8. Could not obtain transaction-synchronized Session for current thread 错误的解决方法!

    BsTable bsTable = new BsTable(); // String time = request.getParameter("date"); String tim ...

  9. Spring+Hibernate4 Junit 报错No Session found for current thread

    论坛上有另外一篇更全面的帖子,jinnianshilongnian写的:http://www.iteye.com/topic/1120924 本文的环境是:  spring-framework-3.1 ...

随机推荐

  1. java集合-集合大家族

    在编写 Java 程序中,我们最常用的除了八种基本数据类型,String 对象外还有一个集合类,在我们的的程序中到处充斥着集合类的身影!Java 中集合大家族的成员实在是太丰富了,有常用的 Array ...

  2. Typescript 中类的继承

    Typescript中类的定义与继承与后端开发语言java/C#等非常像,实现起来非常方便,而且代码便于阅读. 用Typescript写较大项目时是非常有优势的. /** * BaseClass */ ...

  3. [deviceone开发]-企业OA项目开源分享

    一.简介 是一个真实的企业OA项目改造的开源项目,几乎涵盖了所有常用的组件,包括环信实现在线聊天等功能,类似微信的朋友圈功能,自定义的智能搜索等,而且这个是真实的通过Http链接后台web服务,里面很 ...

  4. 系统安装LOL等游戏后出现VS调试报错"无法调试""拒绝访问"之类的调试错误

    一个问题抠得脑壳痛,度娘一番各种各样的答案.基本属于 1,调试权限被清0 2,文件权限问题   其中看到很多解决方案中提到"重启电脑"的说法.我也试了几次不行甚至游戏都卸载了.后来 ...

  5. github-ssh

        # lsb_release -a    No LSB modules are available.    Distributor ID:    Ubuntu    Description:   ...

  6. Kotlin语法(函数和lambda表达式)

    三.函数和lambda表达式 1. 函数声明 fun double(x: Int): Int { } 函数参数是用 Pascal 符号定义的 name:type.参数之间用逗号隔开,每个参数必须指明类 ...

  7. Android Design Principles

    Android Design Principles Enchant Me Delight me in surprising ways 用惊奇的方式取悦用户 漂亮的界面,仔细放置的动画,一个恰到时机的音 ...

  8. PCM(Pulse-code modulation)脉冲编码调制

    在音频处理中,我们会经常听到PCM数据,那么什么是PCM数据呢? PCM数据就是模拟信号经过PCM以后的数字信号,PCM就是把音频信号由模拟信号(时间连续,取值连续)转为数字信号(时间离散,取值离散) ...

  9. switch-枚举

    在swift中,如果switch的枚举,可以不写default,因为系统知道有多少种情况,如果不是枚举,必须要写default enum WBComposeToolBarButtonType:Int ...

  10. Android 视频播放器 VideoView 的使用,播放本地视频 和 网络 视频

    1.布局文件 <?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:and ...