Spring 管理hibernate中的事务1(手动开关事务,Aop拦截)

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>












  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值