2013-02-06 45 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 –

相关问题