Sping3.1和hibernate4.2集成—— No Session found for current thread

在使用spring3和hibernate4.2集成与hibernate3有很多的不同,其中之一就是spring3不在支持HibernateTemplate,而是使用hibernate原生的api,我在集成的时候遇到了如下两个问题。

[color=red]问题之一:在使用session.save()方法保存数据时不能成功的保存到数据库[/color]
这个问题的原因是在获取session时,不能使用openSession()方法,而要使用getCurrentSession()方法
	
@Resource(name="sf")
private SessionFactory sessionFactory;
Session session ;
...
session = sessionFactory.getCurrentSession();


[color=red]问题之二:使用getCurrentSession时报:hibernate4 org.hibernate.HibernateException: No Session的错误[/color]
这个问题的原因是session未打开,解决方式:
前提记得在service层上面加上@Transaction注释,否则任然会有相同的异常

方式1-在web.xml中加过滤器
	<!-- open session filter -->
<filter>
<filter-name>openSessionInViewFilter</filter-name>
<filter-class>org.springframework.orm.hibernate4.support.OpenSessionInViewFilter</filter-class>
<init-param>
<param-name>singleSession</param-name>
<param-value>true</param-value>
</init-param>
</filter>

方式2-配置事务的切面
	<!-- 用spring管理事务 -->
<bean id="transactionManager" class="org.springframework.orm.hibernate4.HibernateTransactionManager">
<property name="sessionFactory" ref="sf"/>
</bean>

<!-- 配置使用注解的方式来使用事务 -->
<tx:annotation-driven transaction-manager="transactionManager" />

<!-- 配置那些类的方法进行事务管理,需要aopalliance-1.0.jar和aspectjweaver.jar,当前com.neusoft.leehom.service包中的子包,
类中所有方法需要,还需要参考tx:advice的设置 -->

<!-- 这是事务通知操作,使用的事务管理器引用自 transactionManager -->
<tx:advice id="txAdvice" transaction-manager="transactionManager">
<tx:attributes>

<tx:method name="insert*" propagation="REQUIRED" />
<tx:method name="update*" propagation="REQUIRED" />
<tx:method name="delete*" propagation="REQUIRED" />
<tx:method name="get*" propagation="REQUIRED" read-only="true"/>
<tx:method name="query*" propagation="REQUIRED" read-only="true"/>
<tx:method name="*" propagation="REQUIRED" />
</tx:attributes>
</tx:advice>

<!-- 需要引入aop的命名空间 -->
<aop:config>
<!-- 切入点指明了在执行Service的所有方法时产生事务拦截操作 -->
<aop:pointcut id="daoMethods" expression="execution(* com.tl..serviceimpl.*.*(..))" />
<!-- 定义了将采用何种拦截操作,这里引用到 txAdvice -->
<aop:advisor advice-ref="txAdvice" pointcut-ref="daoMethods" />
</aop:config>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值