`
michaelxz
  • 浏览: 20768 次
  • 性别: Icon_minigender_1
  • 来自: 遂宁
社区版块
存档分类
最新评论

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(invocation.getMethod());

 

       if (txAttr == null || !(getTransactionManager() instanceof CallbackPreferringPlatformTransactionManager)) {

           // Standard transaction demarcation with getTransaction and commit/rollback calls.

// createTransactionIfNecessary 参见3

           TransactionInfo txInfo = createTransactionIfNecessary(txAttr, joinpointIdentification);

           Object retVal = null;

           try {

              // This is an around advice: Invoke the next interceptor in the chain.

              // This will normally result in a target object being invoked.

              retVal = invocation.proceed();

           }

           catch (Throwable ex) {

              // target invocation exception

              completeTransactionAfterThrowing(txInfo, ex);

              throw ex;

           }

           finally {

              cleanupTransactionInfo(txInfo);

           }

           commitTransactionAfterReturning(txInfo);

           return retVal;

       }

 

       else {

           // It's a CallbackPreferringPlatformTransactionManager: pass a TransactionCallback in.

           try {

              Object result = ((CallbackPreferringPlatformTransactionManager) getTransactionManager()).execute(txAttr,

                     new TransactionCallback() {

                         public Object doInTransaction(TransactionStatus status) {

                            TransactionInfo txInfo = prepareTransactionInfo(txAttr, joinpointIdentification, status);

                            try {

                                return invocation.proceed();

                            }

                            catch (Throwable ex) {

                                if (txAttr.rollbackOn(ex)) {

                                   // A RuntimeException: will lead to a rollback.

                                   if (ex instanceof RuntimeException) {

                                       throw (RuntimeException) ex;

                                   }

                                   else {

                                       throw new ThrowableHolderException(ex);

                                   }

                                }

                                else {

                                   // A normal return value: will lead to a commit.

                                   return new ThrowableHolder(ex);

                                }

                            }

                            finally {

                                cleanupTransactionInfo(txInfo);

                            }

                         }

                     });

 

              // Check result: It might indicate a Throwable to rethrow.

              if (result instanceof ThrowableHolder) {

                  throw ((ThrowableHolder) result).getThrowable();

              }

              else {

                  return result;

              }

           }

           catch (ThrowableHolderException ex) {

              throw ex.getCause();

           }

       }

    }

 

 

3. TransactionAspectSupportcreateTransactionIfNecessary方法

protected TransactionInfo createTransactionIfNecessary(

           TransactionAttribute txAttr, final String joinpointIdentification) {

 

       // If no name specified, apply method identification as transaction name.

       if (txAttr != null && txAttr.getName() == null) {

           txAttr = new DelegatingTransactionAttribute(txAttr) {

              public String getName() {

                  return joinpointIdentification;

              }

           };

       }

 

       TransactionStatus status = null;

       if (txAttr != null) {

//此处获取你的平台事务,我们这里是HiberanteTransactionManager

           PlatformTransactionManager tm = getTransactionManager();

           if (tm != null) {

//此处开始获取事务,里面的一些列动作都相当重要,开发中很多的错误信息都是从这个里面报出来的

参见4

              status = tm.getTransaction(txAttr);

           }

           else {

              if (logger.isDebugEnabled()) {

                  logger.debug("Skipping transactional joinpoint [" + joinpointIdentification +

                         "] because no transaction manager has been configured");

              }

           }

       }

       return prepareTransactionInfo(txAttr, joinpointIdentification, status);

    }

 

  

 

 

4.

AbstractPlatformTransactionManager

public final TransactionStatus getTransaction(TransactionDefinition definition) throws TransactionException {

//取到一个事务对象,参看5

       Object transaction = doGetTransaction();

 

       // Cache debug flag to avoid repeated checks.

       boolean debugEnabled = logger.isDebugEnabled();

 

       if (definition == null) {

           // Use defaults if no transaction definition given.

           definition = new DefaultTransactionDefinition();

       }

 

//判断当前transaction对象中是否真正存在事务了,底层的判断其实就是判断当前transaction中是否SessionHolder为null, SessionHolder中的transaction属性是否为null,SessionHolder中的session属性的transaction属性是否为null,此处以为false

       

if (isExistingTransaction(transaction)) {

           // Existing transaction found -> check propagation behavior to find out how to behave.

           return handleExistingTransaction(definition, transaction, debugEnabled);

       }

 

       // Check definition settings for new transaction.

       if (definition.getTimeout() < TransactionDefinition.TIMEOUT_DEFAULT) {

           throw new InvalidTimeoutException("Invalid transaction timeout", definition.getTimeout());

       }

 

       // No existing transaction found -> check propagation behavior to find out how to proceed.

       if (definition.getPropagationBehavior() == TransactionDefinition.PROPAGATION_MANDATORY) {

           throw new IllegalTransactionStateException(

                  "No existing transaction found for transaction marked with propagation 'mandatory'");

       }

       else if (definition.getPropagationBehavior() == TransactionDefinition.PROPAGATION_REQUIRED ||

              definition.getPropagationBehavior() == TransactionDefinition.PROPAGATION_REQUIRES_NEW ||

           definition.getPropagationBehavior() == TransactionDefinition.PROPAGATION_NESTED) {

           SuspendedResourcesHolder suspendedResources = suspend(null);

           if (debugEnabled) {

              logger.debug("Creating new transaction with name [" + definition.getName() + "]: " + definition);

           }

           try {

//此处就是传说中的真正事务和Session的操作入口

参见 6

              doBegin(transaction, definition);

           }

           catch (RuntimeException ex) {

              resume(null, suspendedResources);

              throw ex;

           }

           catch (Error err) {

              resume(null, suspendedResources);

              throw err;

           }

           boolean newSynchronization = (getTransactionSynchronization() != SYNCHRONIZATION_NEVER);

           return newTransactionStatus(

                  definition, transaction, true, newSynchronization, debugEnabled, suspendedResources);

       }

       else {

           // Create "empty" transaction: no actual transaction, but potentially synchronization.

           boolean newSynchronization = (getTransactionSynchronization() == SYNCHRONIZATION_ALWAYS);

           return newTransactionStatus(definition, null, true, newSynchronization, debugEnabled, null);

       }

    }

  

 

 

 

 

5.

HibernateTransactionManager

protected Object doGetTransaction() {

// HibernateTransactionObject参见前面的类说明

       HibernateTransactionObject txObject = new HibernateTransactionObject();

       txObject.setSavepointAllowed(isNestedTransactionAllowed());

 

//此方法是取出与当前线程绑定SessionHolder,此处取出为null

       SessionHolder sessionHolder =

              (SessionHolder) TransactionSynchronizationManager.getResource(getSessionFactory());

       if (sessionHolder != null) {

           if (logger.isDebugEnabled()) {

              logger.debug("Found thread-bound Session [" +

                     SessionFactoryUtils.toString(sessionHolder.getSession()) + "] for Hibernate transaction");

           }

           txObject.setSessionHolder(sessionHolder);

       }

       else if (this.hibernateManagedSession) {

           try {

              Session session = getSessionFactory().getCurrentSession();

              if (logger.isDebugEnabled()) {

                  logger.debug("Found Hibernate-managed Session [" +

                         SessionFactoryUtils.toString(session) + "] for Spring-managed transaction");

              }

              txObject.setExistingSession(session);

           }

           catch (HibernateException ex) {

              throw new DataAccessResourceFailureException(

                     "Could not obtain Hibernate-managed Session for Spring-managed transaction", ex);

           }

       }

 

       if (getDataSource() != null) {

    //此处取出与当前线程绑定的ConnectionHolder,此处为null     

           ConnectionHolder conHolder = (ConnectionHolder)

    TransactionSynchronizationManager.getResource(getDataSource());

           txObject.setConnectionHolder(conHolder);

       }

       return txObject;

    }

  

 

 

6.

protected void doBegin(Object transaction, TransactionDefinition definition) {

       HibernateTransactionObject txObject = (HibernateTransactionObject) transaction;

 

       if (txObject.hasConnectionHolder() && !txObject.getConnectionHolder().isSynchronizedWithTransaction()) {

           throw new IllegalTransactionStateException(

                  "Pre-bound JDBC Connection found! HibernateTransactionManager does not support " +

                  "running within DataSourceTransactionManager if told to manage the DataSource itself. " +

                  "It is recommended to use a single HibernateTransactionManager for all transactions " +

                  "on a single DataSource, no matter whether Hibernate or JDBC access.");

       }

 

       Session session = null;

 

       try {

           if (txObject.getSessionHolder() == null || txObject.getSessionHolder().isSynchronizedWithTransaction()) {

//此处可以获取注入的Hibernate的实体拦截器

              Interceptor entityInterceptor = getEntityInterceptor();

//在此处获取了一个session

              Session newSession = (entityInterceptor != null ?

                     getSessionFactory().openSession(entityInterceptor) : getSessionFactory().openSession());

              if (logger.isDebugEnabled()) {

                  logger.debug("Opened new Session [" + SessionFactoryUtils.toString(newSession) +

                         "] for Hibernate transaction");

              }

//将session放入txObject中,此处的实际操作是

public void setSession(Session session) {

           this.sessionHolder = new SessionHolder(session);

           this.newSessionHolder = true;

           this.newSession = true;

       }
 


 

              txObject.setSession(newSession);

           }

 

           session = txObject.getSessionHolder().getSession();

 

           if (this.prepareConnection && isSameConnectionForEntireSession(session)) {

              // We're allowed to change the transaction settings of the JDBC Connection.

              if (logger.isDebugEnabled()) {

                  logger.debug(

                         "Preparing JDBC Connection of Hibernate Session [" + SessionFactoryUtils.toString(session) + "]");

              }

              Connection con = session.connection();

              Integer previousIsolationLevel = DataSourceUtils.prepareConnectionForTransaction(con, definition);

              txObject.setPreviousIsolationLevel(previousIsolationLevel);

           }

           else {

              // Not allowed to change the transaction settings of the JDBC Connection.

              if (definition.getIsolationLevel() != TransactionDefinition.ISOLATION_DEFAULT) {

                  // We should set a specific isolation level but are not allowed to...

                  throw new InvalidIsolationLevelException(

                         "HibernateTransactionManager is not allowed to support custom isolation levels: " +

                         "make sure that its 'prepareConnection' flag is on (the default) and that the " +

                         "Hibernate connection release mode is set to 'on_close' (SpringTransactionFactory's default). " +

                         "Make sure that your LocalSessionFactoryBean actually uses SpringTransactionFactory: Your " +

                         "Hibernate properties should *not* include a 'hibernate.transaction.factory_class' property!");

              }

              if (logger.isDebugEnabled()) {

                  logger.debug(

                         "Not preparing JDBC Connection of Hibernate Session [" + SessionFactoryUtils.toString(session) + "]");

              }

           }

//如果事务级别是readOnly就会将session的FlushMode设置NEVER

           if (definition.isReadOnly() && txObject.isNewSession()) {

              // Just set to NEVER in case of a new Session for this transaction.

              session.setFlushMode(FlushMode.NEVER);

           }

 

           if (!definition.isReadOnly() && !txObject.isNewSession()) {

              // We need AUTO or COMMIT for a non-read-only transaction.

              FlushMode flushMode = session.getFlushMode();

              if (flushMode.lessThan(FlushMode.COMMIT)) {

                  session.setFlushMode(FlushMode.AUTO);

                  txObject.getSessionHolder().setPreviousFlushMode(flushMode);

              }

           }

 

           Transaction hibTx = null;

 

           // Register transaction timeout.

           int timeout = determineTimeout(definition);

           if (timeout != TransactionDefinition.TIMEOUT_DEFAULT) {

              // Use Hibernate's own transaction timeout mechanism on Hibernate 3.1

              // Applies to all statements, also to inserts, updates and deletes!

              hibTx = session.getTransaction();

              hibTx.setTimeout(timeout);

              hibTx.begin();

           }

           else {

              // Open a plain Hibernate transaction without specified timeout.

              //传说中真正的获取到一个transaction

              hibTx = session.beginTransaction();

           }

 

           // Add the Hibernate transaction to the session holder.

           //将这个事务放入SessionHolder中

           txObject.getSessionHolder().setTransaction(hibTx);

 

           // Register the Hibernate Session's JDBC Connection for the DataSource, if set.

           if (getDataSource() != null) {

              Connection con = session.connection();

              ConnectionHolder conHolder = new ConnectionHolder(con);

              if (timeout != TransactionDefinition.TIMEOUT_DEFAULT) {

                  conHolder.setTimeoutInSeconds(timeout);

              }

              if (logger.isDebugEnabled()) {

                  logger.debug("Exposing Hibernate transaction as JDBC transaction [" + con + "]");

              }

              TransactionSynchronizationManager.bindResource(getDataSource(), conHolder);

              txObject.setConnectionHolder(conHolder);

           }

 

           // Bind the session holder to the thread.

           if (txObject.isNewSessionHolder()) {

           //将当前线程与SessionHolder绑定    TransactionSynchronizationManager.bindResource(getSessionFactory(), txObject.getSessionHolder());

           }

           txObject.getSessionHolder().setSynchronizedWithTransaction(true);

       }

 

       catch (Exception ex) {

           if (txObject.isNewSession()) {

              try {

                  if (session.getTransaction().isActive()) {

                     session.getTransaction().rollback();

                  }

              }

              catch (Throwable ex2) {

                  logger.debug("Could not rollback Session after failed transaction begin", ex);

              }

              finally {

                  SessionFactoryUtils.closeSession(session);

              }

           }

           throw new CannotCreateTransactionException("Could not open Hibernate Session for transaction", ex);

       }

    }

  

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics