spring事务

spring的事务分析

关键字: spring的事务分析

先主要介绍几个核心类

PlatformTransactionManager(平台事务管理)

 

TransactionStatus(事务状态)

 

TransactionDefinition(事务的级别和传播方式)

 

整个PlatformTransactionManager接口提供了一下3个方法

 

 

public interface TransactionStatus extends SavepointManager {

 

    boolean isNewTransaction();

 

     boolean hasSavepoint();

 

     void setRollbackOnly();

 

    boolean isRollbackOnly();

 

    boolean isCompleted();

 

}

public interface TransactionDefinition {

 

    int PROPAGATION_REQUIRED = 0;//支持现有事务。如果没有则创建一个事务

 

    int PROPAGATION_SUPPORTS = 1;//支持现有事务。如果没有则以非事务状态运行。

 

    int PROPAGATION_MANDATORY = 2;//支持现有事务。如果没有则抛出异常。

 

    int PROPAGATION_REQUIRES_NEW = 3;//总是发起一个新事务。如果当前已存在一个事务,则将其挂起。

 

    int PROPAGATION_NOT_SUPPORTED = 4;//不支持事务,总是以非事务状态运行,如果当前存在一个事务,则将其挂起。

 

    int PROPAGATION_NEVER = 5;//不支持事务,总是以非事务状态运行,如果当前存在一个事务,则抛出异常。

 

    int PROPAGATION_NESTED = 6;//如果当前已经存在一个事务,则以嵌套事务的方式运行,如果当前没有事务,则以默认方式(第一个)执行

 

    int ISOLATION_DEFAULT = -1;//默认隔离等级

 

    int ISOLATION_READ_UNCOMMITTED = Connection.TRANSACTION_READ_UNCOMMITTED;//最低隔离等级,仅仅保证了读取过程中不会读取到非法数据

 

    int ISOLATION_READ_COMMITTED = Connection.TRANSACTION_READ_COMMITTED;//某些数据库的默认隔离等级;保证了一个事务不会读到另外一个并行事务已修改但未提交的数据

 

    int ISOLATION_REPEATABLE_READ = Connection.TRANSACTION_REPEATABLE_READ;//比上一个更加严格的隔离等级。保证了一个事务不会修改已经由另一个事务读取但未提交(回滚)的数据

 

    int ISOLATION_SERIALIZABLE = Connection.TRANSACTION_SERIALIZABLE;//性能代价最为昂贵,最可靠的隔离等级。所有事务都严格隔离,可视为各事务顺序执

 

   int TIMEOUT_DEFAULT = -1;

 

    int getPropagationBehavior();

 

    int getIsolationLevel();

 

    int getTimeout();

 

    boolean isReadOnly(); 

 

    String getName();

 

 

}

 

 

 

HibernateTransactionObject 

此类具有以下3个常用参数

 

private SessionHolder sessionHolder;

 

private boolean newSessionHolder;

 

private boolean newSession;

 

SessionHolder

是spring定义的一个类,将事务和session包装在一起

    private static final Object DEFAULT_KEY = new Object();

 

    private final Map sessionMap = Collections.synchronizedMap(new HashMap(1));

 

    private Transaction transaction;

 

    private FlushMode previousFlushMode;

 

 

 下面将大致讲讲以拦击器管理事务的方式

<bean id="proxyFactory"    class="org.springframework.aop.framework.autoproxy.BeanNameAutoProxyCreator">

       <property name="beanNames">

           <list>

              <value>businessOrderDao</value>

           </list>

       </property>

       <property name="interceptorNames">

           <list>

              <value>transactionInterceptor</value>

           </list>

       </property>

    </bean>

 

Spring的事务配置方式之一 :使用拦截器

 

List<GpBusiOrderInfo> all = businessOrderDao.queryAndUpdateGpBusiOrderInfo());

当程序进入这个方法的时候,其实是进入的spring的一个代理中

JdkDynamicAopProxy

 

public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {

 

       MethodInvocation invocation = null;

 

       Object oldProxy = null;

 

       boolean setProxyContext = false;

 

       TargetSource targetSource = this.advised.targetSource;

 

//此处targetSource 的值 =SingletonTargetSource for target object[com.wasu.hestia.orm.dao.hibernate.BusinessOrderInfoDaoImpl@1f0d7f5]

 

//     Class targetClass = null;

 

//     Object target = null;

 

       try {

 

           if (!this.equalsDefined && AopUtils.isEqualsMethod(method)) {

 

              // The target does not implement the equals(Object) method itself.

 

              return (equals(args[0]) ? Boolean.TRUE : Boolean.FALSE);

 

           }

 

           if (!this.hashCodeDefined && AopUtils.isHashCodeMethod(method)) {

 

              // The target does not implement the hashCode() method itself.

 

              return new Integer(hashCode());

 

           }

 

           if (!this.advised.opaque && method.getDeclaringClass().isInterface() &&

 

                  method.getDeclaringClass().isAssignableFrom(Advised.class)) {

 

              // Service invocations on ProxyConfig with the proxy config...

 

              return AopUtils.invokeJoinpointUsingReflection(this.advised, method, args);

 

           }

 

           Object retVal = null;

 

           if (this.advised.exposeProxy) {

 

              // Make invocation available if necessary.

 

              oldProxy = AopContext.setCurrentProxy(proxy);

 

              setProxyContext = true;

 

           }

 

           // May be <code>null</code>. Get as late as possible to minimize the time we "own" the target,

 

           // in case it comes from a pool.

 

           target = targetSource.getTarget();

 

           if (target != null) {

 

              targetClass = target.getClass();

 

           }

 

           // Get the interception chain for this method.

 

           List chain = this.advised.getInterceptorsAndDynamicInterceptionAdvice(method, targetClass);

 

// getInterceptorsAndDynamicInterceptionAdvice 是根据方法和被代理的目标类来获取配置文件中对其进行拦截的操作,在这里只有org.springframework.transaction.interceptor.TransactionInterceptor//@1b1deea]

 

           // Check whether we have any advice. If we don't, we can fallback on direct

 

           // reflective invocation of the target, and avoid creating a MethodInvocation.

 

           if (chain.isEmpty()) {

 

              // We can skip creating a MethodInvocation: just invoke the target directly

 

              // Note that the final invoker must be an InvokerInterceptor so we know it does

 

              // nothing but a reflective operation on the target, and no hot swapping or fancy proxying.

 

              retVal = AopUtils.invokeJoinpointUsingReflection(target, method, args);

 

           }

 

           else {

 

              // We need to create a method invocation...

 

              invocation = new ReflectiveMethodInvocation(proxy, target, method, args, targetClass, chain);

 

这个new了一个ReflectiveMethodInvocation对象,他的基类就是MethodInvocation

 

              // Proceed to the joinpoint through the interceptor chain.

 

              retVal = invocation.proceed();

 

//此方法参见下面 1

 

           }

 

           // Massage return value if necessary.

 

           if (retVal != null && retVal == target && method.getReturnType().isInstance(proxy) &&

 

                  !RawTargetAccess.class.isAssignableFrom(method.getDeclaringClass())) {

 

              // Special case: it returned "this" and the return type of the method

 

              // is type-compatible. Note that we can't help if the target sets

 

              // a reference to itself in another returned object.

 

              retVal = proxy;

 

           }

 

           return retVal;

 

       }

 

       finally {

 

           if (target != null && !targetSource.isStatic()) {

 

              // Must have come from TargetSource.

 

              targetSource.releaseTarget(target);

 

           }

 

           if (setProxyContext) {

 

              // Restore old proxy.

 

              AopContext.setCurrentProxy(oldProxy);

 

           }

 

       }

 

    }

 

 

 

1.

public Object proceed() throws Throwable {

 

       //  We start with an index of -1 and increment early.

 

// currentInterceptorIndex的初始化值为-1,在这里也就是判断是否还有拦截器需要执行

 

       if (this.currentInterceptorIndex == this.interceptorsAndDynamicMethodMatchers.size() - 1) {

 

           return invokeJoinpoint();

 

       }

 

//此出当前currentInterceptorIndex+1的下标的拦截器取出,当前程序是0,对应的拦截器是org.springframework.transaction.interceptor.TransactionInterceptor@1b1deea

 

       Object interceptorOrInterceptionAdvice =      this.interceptorsAndDynamicMethodMatchers.get(++this.currentInterceptorIndex);

 

 

//这里返回false

 

       if (interceptorOrInterceptionAdvice instanceof InterceptorAndDynamicMethodMatcher) {

 

           // Evaluate dynamic method matcher here: static part will already have

 

           // been evaluated and found to match.

 

           InterceptorAndDynamicMethodMatcher dm =

 

               (InterceptorAndDynamicMethodMatcher) interceptorOrInterceptionAdvice;

 

           if (dm.methodMatcher.matches(this.method, this.targetClass, this.arguments)) {

 

              return dm.interceptor.invoke(this);

 

           }

 

           else {

 

              // Dynamic matching failed.

 

              // Skip this interceptor and invoke the next in the chain.

 

              return proceed();

 

           }

 

       }

 

       else {

 

           // It's an interceptor, so we just invoke it: The pointcut will have

 

           // been evaluated statically before this object was constructed.

 

//由于interceptorOrInterceptionAdvice现在是Object类型,所以需要将当前的interceptorOrInterceptionAdvice转换成MethodInterceptor也就是TransactionInterceptor的基类

 

请参看2

           return ((MethodInterceptor) interceptorOrInterceptionAdvice).invoke(this);

 

       }

 

    }

 

  

 

 

 

2.

程序进入了TransactionInterceptor,调用它的invoke方法

public Object invoke(final MethodInvocation invocation) throws Throwable {

 

       // Work out the target class: may be <code>null</code>.

 

       // The TransactionAttributeSource should be passed the target class

 

       // as well as the method, which may be from an interface.

 

//当前的targetClass 就是com.wasu.hestia.orm.dao.hibernate.BusinessOrderInfoDaoImpl

 

       Class targetClass = (invocation.getThis() != null ? invocation.getThis().getClass() : null);

 

 

 

       // If the transaction attribute is null, the method is non-transactional.

 

//根据方法名和目标对象获取TransactionAttribute的属性,此处值为PROPAGATION_REQUIRED,ISOLATION_DEFAULT,其中ISOLATION_DEFAULT是默认的数据库隔离级别

 

       final TransactionAttribute txAttr =               getTransactionAttributeSource().getTransactionAttribute(invocation.getMethod(), targetClass);

 

// joinpointIdentification 的值为com.wasu.hestia.orm.dao.BusinessOrderInfoDao.queryAndUpdateGpBusiOrderInfo

 

       final String joinpointIdentification = methodIdentification(invoc

 

 

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值