Transactions Made Simple Using Speedment 3.0.17 and Above


Sometimes 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.

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.


Imagine 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 ->

    Account sender =

    Account receiver =

    accounts.update(sender.setBalance(sender.getBalance() - 100));
    accounts.update(receiver.setBalance(receiver.getBalance() + 100));


When the method 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).


Before transactions can be used, we need to obtain a TransactionHandler like this:

BankApplication app = ....
    TransactionComponent transactionComponent = app.getOrThrow(TransactionComponent.class);
    TransactionHandler txHandler = transactionComponent.createTransactionHandler();

The AccountManager can 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 .

稿源:Minborg's Java Pot (源链) | 关于 | 阅读提示

本站遵循[CC BY-NC-SA 4.0]。如您有版权、意见投诉等问题,请通过eMail联系我们处理。
酷辣虫 » 后端存储 » Transactions Made Simple Using Speedment 3.0.17 and Above

喜欢 (0)or分享给?

专业 x 专注 x 聚合 x 分享 CC BY-NC-SA 4.0

使用声明 | 英豪名录