1.手动通过Aop环绕拦截,为业务方法前后开关事务。(通过当前线程来开启的)
例子:
LoggAop.java:
package org.hzy.aop;
import org.aopalliance.intercept.MethodInterceptor;
import org.aopalliance.intercept.MethodInvocation;
import org.hibernate.SessionFactory;
public class LoggAop implements MethodInterceptor{
private SessionFactory sf;
public SessionFactory getSf() {
return sf;
}
public void setSf(SessionFactory sf) {
this.sf = sf;
}
public Object invoke(MethodInvocation arg0) throws Throwable {
// TODO Auto-generated method stub
System.out.println("begin");
this.sf.getCurrentSession().beginTransaction();
Object o=arg0.proceed();
this.sf.getCurrentSession().getTransaction().commit();
System.out.println("end");
return o;
}
}
配置:
<prop key="hibernate.current_session_context_class">thread</prop>
<aop:config>
<bean id="LogAop" class="org.hzy.aop.LoggAop">
<property name="sf" ref="MySessionFactory" />
</bean>
<aop:config>
<aop:pointcut expression="execution(* org.hzy.services.impl.DeptService.*(..))" id="tx"/>
<aop:advisor advice-ref="LogAop" pointcut-ref="tx"/>
<!-- 此处和上面method方法相同
<aop:aspect ref="ad_aop">
<aop:around method="handler_tx" pointcut="execution(* org.accp.services.UserService.findDept(..))"/>
</aop:aspect>
-->
</aop:config>
上面的配置是我们手动的开启事务,使用Aop切割,LoggAop中需要提供一个SessionFactory,因为使用手动的事务需要将Session绑定到线程当中
<prop key="hibernate.current_session_context_class">thread</prop>
1476

被折叠的 条评论
为什么被折叠?



