[英]Do we really need to set the Transaction in ThreadLocal?
我粘貼了下面的代碼。 在我們的應用程序中,他們在線程本地設置事務。
其實我懷疑為什么我們需要這個呢?
如果我們沒有在threadlocal中設置tranaction會發生什么?
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為例)。
如果您沒有在本地線程上設置事務,則可能會發生兩件事
你有沒有看到更好的方式來做這個阿達拉?
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.