Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/361.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 我们真的需要在ThreadLocal中设置事务吗?_Java_Database_Multithreading_Transactions_Thread Local - Fatal编程技术网

Java 我们真的需要在ThreadLocal中设置事务吗?

Java 我们真的需要在ThreadLocal中设置事务吗?,java,database,multithreading,transactions,thread-local,Java,Database,Multithreading,Transactions,Thread Local,我把代码贴在下面。在我们的应用程序中,他们将事务设置为本地线程。 实际上我的疑问是我们为什么需要这个 如果我们没有在threadlocal中设置Transaction,会发生什么 public void beginTransaction() { final String METHOD_NAME = "beginTransaction"; log.entering(CLASS_NAME, METHOD_NAME); PcUtilLogging.logTransactio

我把代码贴在下面。在我们的应用程序中,他们将事务设置为本地线程。
实际上我的疑问是我们为什么需要这个 如果我们没有在threadlocal中设置Transaction,会发生什么

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;
}

问题在于,人们希望从应用程序的不同部分(例如不同的DAO)访问事务,因此通常采用这种方式,以避免在应用程序中传递事务对象(并将持久性逻辑泄漏到应用程序中)

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

如果不在本地线程上设置事务,则可能会发生两种情况

  • 每个数据库访问都需要使用不同的事务
  • 所有事务都是混合的,因为一个请求上的提交会影响不同线程上的更改
阿达拉,你有没有更好的办法