| | |
|
|
|
Database transaction patterns
The following types of database transactions are covered in this article.
Local transactions
Local database transactions are supported using the Manager.inTransaction method. This method provides the convenience to implicitly demarcate the transaction boundaries. The zero.data.Manager version of inTransaction takes an implementation of zero.data.LocalTransaction whereas the zero.data.groovy.Manager version simply takes a closure as shown in the following example:
import zero.data.LocalTransaction;
import zero.data.Manager;
// Java code:
Manager voteDB = Manager.create("votingDB");
voteDB.inTransaction(new LocalTransaction() {
public void execute() {
voteDB.update("INSERT...");
voteDB.update("UPDATE...");
voteDB.update("DELETE...");
}
});
// Groovy code:
def voteDB = zero.data.groovy.Manager.create('votingDB')
voteDB.inTransaction {
voteDB.update("INSERT...")
voteDB.update("UPDATE...")
voteDB.update("DELETE...")
}
During the inTransaction demarcation, all query calls use the same Connection. If an exception is thrown either from query calls or explicitly by the application, the the local transaction is rolled back. Otherwise, the transaction is committed and the Connection is closed. For example, the following code illustrates manually throwing an exception based on a condition:
// Java code:
import zero.data.Manager;
...
Manager voteDB = Manager.create("votingDB");
voteDB.inTransaction(new LocalTransaction() {
public void execute() {
voteDB.update("INSERT...");
voteDB.update("UPDATE...");
if (/* some condition */)
throw new Exception("...");
}
});
// Groovy code:
def voteDB = zero.data.groovy.Manager.create('votingDB')
voteDB.inTransaction {
voteDB.update("INSERT...")
voteDB.update("UPDATE...")
if (/* some condition */)
throw new Exception("...");
}
Manual transactions
Transaction demarcation can also be done using a programmatic interface. The following methods are provided:
-
beginTransaction()
-
commitTransaction()
-
rollbackTransaction()
The implicit local transaction shown in the previous example can also be achieved by doing the following:
data.startTransaction();
try {
data.update("INSERT...");
data.update("UPDATE...");
data.update("DELETE...");
data.commitTransaction();
catch (Exception e) {
data.rollbackTransaction();
} finally {
data.endTransaction();
}
|
|
r3 - 18 Jan 2008 - 14:56:16 - paynel
|
|
|
| | |