2013-02-06 44 views
0

我在下面粘貼了我的代碼。在我們的應用程序中,他們在線程本地設置事務。
其實我的疑問是爲什麼我們需要這個?
如果我們沒有在threadlocal中設置tranaction會發生什麼?我們是否真的需要在ThreadLocal中設置事務?

public void beginTransaction() { 

    final String METHOD_NAME = "beginTransaction"; 
    log.entering(CLASS_NAME, METHOD_NAME); 

    PcUtilLogging.logTransactionLifecycle("Begin Transaction", 
      this.persistenceConfigurationKey); 

    // Initialize. 
    final PcRequestContext context = PcRequestContext.getInstance(); 
    final PersistenceManager pm = 
      context.getPersistenceManager(this.persistenceConfigurationKey); 

    try { 
     // Begin a new transaction. 
     final Transaction transaction = pm.newTransaction(); 

     // Set the Transaction in ThreadLocal. 
     context.setTransaction(this.persistenceConfigurationKey, 
       transaction); 

    } catch (final Exception e) { 

     // Throw. 
     throw new PcTransactionException(
       new ApplicationExceptionAttributes.Builder(CLASS_NAME, METHOD_NAME).build(), 
       "Error encountered while attempting to begin a [" 
         + this.getPersistenceConfigurationKey() 
         + "] transaction.", e); 
    } 

    log.exiting(CLASS_NAME, METHOD_NAME); 
    return; 
} 

回答

1

的問題是,一個人想從您的應用程序的不同部分(不同的DAO例如)訪問該事務,所以它通常這樣做是爲了避免通過在應用程序中的交易對象(和將持久性邏輯泄漏到您的應用程序中)。

此外,事務通常與接受請求(或jms消息)的線程相關,所以ThreadLocal是一個方便的地方。大多數框架都是這樣做的(以Spring爲例)。

如果您沒有設置交易上一個線程局部有兩種情況

  • 每個DB訪問需要使用不同的交易。
  • 所有事務混淆在一起,因爲對一個請求的提交會影響不同線程上的更改。

您是否看到有更好的方式來做這個Adala?

+0

thanks @augusto –

相關問題