Transactions Trail
This trail assumes, that you are already familar with the general meaning of transactions. It shows you, how to start, commit and rollback transactions.
When to use transactions
The short anser is always.
Whenever you want to read, write or search persistent data,
this must happen within the boundaries of a transaction.
These boundaries are marked by calls to the methods
Model.startTransaction()
and Model.commit()
or Model.rollback()
.
Any attempt to access persistent data outside a transaction will cause an exception. There is no equivalent to what is known as auto-commit in relational databases.
Example
Since you also have to take care of exceptions, the standard way of using transactions looks like this:
boolean failure = true; try { Main.model.startTransaction(); // put the body of the transaction here Main.model.commit(); failure = false; } finally { if(failure) Main.model.rollback(); }
For your convenience, the framework provides a method
Model.rollbackIfNotCommitted()
which does a rollback if and only if the transaction
has not been closed (committed or rolled back) before.
Therefore you can make the code a little bit shorter:
try { Main.model.startTransaction(); // put the body of the transaction here Main.model.commit(); } finally { Main.model.rollbackIfNotCommitted(); }
For even more convenience you may use the try-with-resources syntax introduced in Java 1.7:
try(TransactionTry tx = Main.model.startTransactionTry("web")) { // put the body of the transaction here tx.commit(); }
Further Reading
There is not much more to say about transactions, so you may want to proceed to any of the following trails:
- Searching Trail gives you an introduction into the searching capabilities of exedio persistence.
- Field Reloaded Trail covers all the more specific possibilities to store data with exedio persistence.
- Web Application Trail shows you the little differences when using the framework within a web container. This includes a helper class for managing transactions as well.