No Hibernate Session bound to thread, and configuration does not allow creation of non-transactional one here
没有Hibernate会话绑定到线程,并且配置不允许在这里创建非事务性会话。
我的代码出现这种情况是因为多线程处理list的时候,Hibernate Session配置的问题。
解决办法是在applicationContext.xml中
增加如下配置:
<bean id="transactionManager"
class="org.springframework.orm.hibernate3.HibernateTransactionManager">
<property name="sessionFactory">
<ref local="sessionFactory" />
</property>
</bean>
<tx:annotation-driven transaction-manager="transactionManager"/>
这里需要注意的是
<tx:advice id="txAdvice" transaction-manager="transactionManager">
<tx:attributes>
<!--保存-->
<tx:method name="save*" propagation="REQUIRED" rollback-for="Exception"/>
<!--修改-->
<tx:method name="update*" propagation="REQUIRED" rollback-for="Exception"/>
<!--删除-->
<tx:method name="delete*" propagation="REQUIRED" rollback-for="Exception"/>
<!--驱动-->
<tx:method name="do*" propagation="REQUIRED" rollback-for="Exception"/>
<!--查询一条-->
<tx:method name="find*" />
<!--查询列表-->
<tx:method name="list*" />
<!--个数-->
<tx:method name="count*" />
<!--统计-->
<tx:method name="statics*" />
<!--其他-->
<tx:method name="*"/>
</tx:attributes>
</tx:advice>
这种事务控制的方式:
<tx:advice id="txAdvice" transaction-manager="transactionManager">
和<tx:annotation-driven transaction-manager="transactionManager"/>
是有区别的。在多线程中,tx:advice控制事务会报以上的错。加上 tx:annotation-driven就可以了。两种配置方式可以同时存在。
<tx:advice的使用方法详情请参考:
https://www.cnblogs.com/hq233/p/6664798.html
<tx:annotation-driven的使用方法详情请参考链接:
https://www.cnblogs.com/cnsdhzzl/p/6061171.html
五种不同的配置方式:
https://blog.youkuaiyun.com/qq_29301417/article/details/78830920
如果以上均不能解决问题。或者事务回滚无效的话。手动添加事务类
//事务,线程内Spring无法管理事务,若一处报错,之前操作的无法正常回滚
DefaultTransactionDefinition def = new DefaultTransactionDefinition();
def.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRED);
PlatformTransactionManager txManager = ContextLoader.getCurrentWebApplicationContext().getBean(PlatformTransactionManager.class);
TransactionStatus status = txManager.getTransaction(def);
try {
//在这里做你想做的事^_^
txManager.commit(status);//线程内事务提交
} catch (Exception e) {
e.printStackTrace();
txManager.rollback(status);//报错,线程内事务回滚
logger.error("AuthRuleResultGeneratorEngine is error", e);
}
这样之后就可以正常提交事务及回滚了。对了,是这个包下的:
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.TransactionDefinition;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.support.DefaultTransactionDefinition;