A SERVICE OF

logo

Chapter 9. Persistence Tutorial 91
9.7.2. Manual Transaction Management
When you manage your transactions locally, your starting point is the SessionManager class. From
there, you can get access to the Session class and then to the Transaction. Specifically, the Session
provides accessto theTransactionContext, whichhas methodsfor beginning atransaction, committing
a transaction, and aborting a transaction. For example, the following code will open a transaction,
execute the necessary code and then either commit or abort the transaction:
import com.arsdigita.persistence.Session;
import com.arsdigita.persistence.SessionManager;
import com.arsdigita.persistence.TransactionContext;
Session session = SessionManager.getSession();
TransactionContext txn = session.getTransactionContext();
try {
txn.beginTxn();
// do some work here
txn.commitTxn();
} catch (Exception e) {
txn.abortTxn();
}
Transactions cannot be nested. If you have to make sure that you are in a transaction, use the inTxn()
method of TransactionContext, as in the following example:
import com.arsdigita.persistence.Session;
import com.arsdigita.persistence.SessionManager;
import com.arsdigita.persistence.TransactionContext;
Session session = SessionManager.getSession();
TransactionContext txn = session.getTransactionContext();
boolean openedTransaction = false;
try {
if (!txn.inTxn()) {
openedTransaction = true;
txn.beginTxn();
}
// do some work here
if (openedTransaction) {
txn.commitTxn();
}
} catch (Exception e) {
if (openedTransaction) {
txn.abortTxn();
}
}