openSession出错:蓝萝卜blu Hibernate4中使用getCurrentSession报Could not obtain transaction-synchronized Sessio
2017-12-12 11:17
274 查看
架个spring4+hibernate4的demo,dao层直接注入的sessionFactory,然后用getCurrentSession方法获取session,然后问题来了,直接报错:
提示无法获取当前线程的事务同步session,略微奇怪,这和事务有什么关系..然后百度一下有人说改成用openSession方法就好了,那我又百度了一下这2个方法的区别:
看起来这个getCurrentSession方法的确和事务有点关系.然后我加上事务:
因为我们在写代码的时候逻辑的线程是在serviceImpl,现在是在DaoImpl中,ServiceImpl和DaoImpl是2个不同的线程在getCurrentSession()中,
getCurrentSession会从上下文中获取session,并且会绑定在当前线程,第一调用的时候会创建一个Session实例,如果Sesssion未关闭的时候,后续
多次获取的时同一个Session,当事物开启关闭或者回滚的时候就会自动关闭Session,无需手动关闭。
使用openSessionView需要手动关闭。
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"/> 解决的方式是打开session在web.xml中进行配置:
<!-- 解决 org.hibernate.HibernateException: Could not obtain transaction-synchronized Session for current 出错问题,主要问题是获取当前线程的问题获取不到 --> <filter> <filter-name>SpringOpenSessionInViewFilter</filter-name> <filter-class>org.springframework.orm.hibernate4.support.OpenSessionInViewFilter</filter-class> </filter> <filter-mapping> <filter-name>SpringOpenSessionInViewFilter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping>为什么会在测试的时候出现这个问题
因为我们在写代码的时候逻辑的线程是在serviceImpl,现在是在DaoImpl中,ServiceImpl和DaoImpl是2个不同的线程在getCurrentSession()中,
getCurrentSession会从上下文中获取session,并且会绑定在当前线程,第一调用的时候会创建一个Session实例,如果Sesssion未关闭的时候,后续
多次获取的时同一个Session,当事物开启关闭或者回滚的时候就会自动关闭Session,无需手动关闭。
使用openSessionView需要手动关闭。
相关文章推荐
- synchronized与Lock的区别与使用
- 解决问题记录(1)-使用OleDbProvider连接Oracle出错
- 使用Gradle编译出错Failed converting ECJ parse tree to Lombok
- linux下用gcc编译使用了math库函数的程序出错的解决方法
- AndroidStudio使用出错:Execution failed for task "app:dexDebug"的解决
- 深入理解使用synchronized同步方法和同步代码块的区别
- [转]SMARTY模板中如何使用get,post,request,cookies,sessio...
- 使用caffe时编译出错
- 安卓使用第三方jar包电脑编译通过但是运行出错
- 使用Maven构建javaWeb项目时,启动tomcat出错:严重: Error configuring application listener of class org.springframewo
- 使用java命令运行class文件带包名时出错
- git使用时出错
- Java基础--->09.关于JDK使用旧方法编译出错、警告问题。
- Java 多线程(五)之 synchronized 的使用
- synchronized的使用方法(2)
- andorid中使用activemq出错
- C#中使用ACCESS插入语法出错
- synchronized 关键字的使用
- 使用CocoaPods更新第三方库出错的解决办法
- mac上使用g++编译出错“Undefined symbols for architecture x86_64:” 错误解决办法