在spring中自己控制事物,并且使用 aop 拦截事务,如果需要使用得到当前session,则需要在 hibernate 的 xml 配置文件中添加属性:
hibernate 版本若为 3.x.x
hibernate.current_thread_class=org.hibernate.context.ThreadLocalSessionContext|thread
hibernate 版本若为 4.x.x
hibernate.current_thread_class=org.hibernate.context.interl.ThreadLocalSessionContext|thread
aop 的配置:
<bean id="muser_inter" class="org.aops.MuserAdvice"> <property name="sessionFactory" ref="sessionFactory"></property> </bean> <aop:config> <aop:pointcut expression="execution(* org.services.impl.MuserServiceImpl.login(String, String))" id="login_pointCut" /> <aop:advisor advice-ref="muser_inter" pointcut-ref="login_pointCut" /> </aop:config>
Java 代码:
package org.aops; import org.aopalliance.intercept.MethodInterceptor; import org.aopalliance.intercept.MethodInvocation; import org.hibernate.SessionFactory; public class MuserAdvice implements MethodInterceptor { private SessionFactory sessionFactory; @Override public Object invoke(MethodInvocation arg0) throws Throwable { System.out.println("in"); sessionFactory.getCurrentSession().beginTransaction(); Object obj = arg0.proceed(); System.out.println("out"); sessionFactory.getCurrentSession().getTransaction().commit(); return obj; } public SessionFactory getSessionFactory() { return sessionFactory; } public void setSessionFactory(SessionFactory sessionFactory) { this.sessionFactory = sessionFactory; } }
控制台输出:
in
Hibernate:
select
muser0_.MUID as MUID1_,
muser0_.MUNAME as MUNAME1_,
muser0_.MUPWD as MUPWD1_
from
TEST.MUSER muser0_
where
muser0_.MUNAME=?
and muser0_.MUPWD=?
out