TransactionsSometimes we want to make sure that our database operations are executed atomically and separated from other operations. This is where transactions come into play. A transaction is a set of operation
proposals that may or may not be accepted by the database as an atomic operation. So, either all operations in the transaction are accepted or no operations of the transaction are accepted. Another advantage with transaction is that the state of the database will be locally "frozen" when the transaction starts, so we will not see updates by other threads while in the transaction.
Speedment is an open-source Stream ORM Java Toolkit and Runtime Java tool that wraps an existing database and its tables into Java 8 streams. Later versions of Speedment support database transactions in an easy-to-use way.
UpdatesImagine we are writing a bank application with accounts and we are going to move $100 from one account (1) to another (2). In this case it is important that money does not disappear (i.e. is deducted from 1 but never deposited in 2) or perhaps even worse, will be duplicated (i.e. deposited in 2 but not deducted from 1). This can be assured using a Speedment database transaction like this:
txHandler.createAndAccept(tx ->When the method
Account sender = accounts.stream()
Account receiver = accounts.stream()
accounts.update(sender.setBalance(sender.getBalance() - 100));
accounts.update(receiver.setBalance(receiver.getBalance() + 100));
tx.commit()is called, the two updates are committed to the database atomically and will be visible to all other threads. If we do not call
tx.commit()explicitly then the transaction will be automatically rolled back (i.e. the updates will not have any effect and will be discarded).
PreparationsBefore transactions can be used, we need to obtain a
BankApplication app = ....The
TransactionComponent transactionComponent = app.getOrThrow(TransactionComponent.class);
TransactionHandler txHandler = transactionComponent.createTransactionHandler();
AccountManagercan be retrieved from the application as shown hereunder:
AccountManager accounts = app.getOrThrow(AccountManager.class);
What's Next?Read more on Speedment transactions here.
Visit GitHub and read all about Speedment open-source here.