0

我在下面粘贴了我的代码。在我们的应用程序中,他们将事务设置在线程本地。
实际上我的疑问是我们为什么需要这个?
如果我们没有在 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;
}
4

1 回答 1

2

问题是人们想要从应用程序的不同部分(例如不同的 DAO)访问事务,因此通常以这种方式完成以避免必须在应用程序周围传递事务对象(并将持久性逻辑泄漏到您的应用程序中) .

此外,事务通常与接受请求(或 jms 消息)的线程相关,因此 ThreadLocal 是放置它的方便位置。大多数框架都这样做(以 Spring 为例)。

如果您不在本地线程上设置事务,可能会发生两件事

  • 每个数据库访问都需要使用不同的事务。
  • 所有事务都混合在一起,因为对一个请求的提交会影响不同线程上的更改。

你有没有更好的方法来做这个阿达拉?

于 2013-02-06T13:04:34.110 回答