DZone's Guide to
Learn how you can return values from database transactions in a simple way by using the latest version of the Speedment open-source stream ORM and Java 8/9.
Join the DZone community and get the full member experience.
Just released, a free O’Reilly book on Reactive Microsystems: The Evolution of Microservices at Scale . Brought to you in partnership with Lightbend.
In my previous post, I wrote about how to use Transactions in an easy way using Speedment where we updated two bank accounts atomically. As you all might know, transactions are a way of combining a number of database operation into a single operation that is atomically executed.
But transactions are not only about updating the database but also about performing atomic reads. With Speedment, we can compute values atomically using Java streams and then return the result to something outside the scope of the transaction in an easy way.
Suppose we have a database with films and artists (e.g. using the open-sourced Sakila database content for MySQL) and we would like to count the number of films plus the number of artists in the database in a single transaction. This might be the case if we want to show some kind of database size in a GUI or the like. Here is how it might look:
long sumCount = txHandler.createAndApply(tx -> films.stream().count() + actors.stream().count() );
When the transaction starts, the view of the database is "frozen" so that new films or artist that are inserted into the database by other threads are not visible within the transaction. Thus, we can safely assume that our view is unaffected by other threads.
As can be seen, with really minimal boilerplate code, we can express functions that are to be performed within transactions using Speedment.
Before transactions can be used, we need to obtain a
TransactionHandler like this:
SakilaApplication app = .... TransactionComponent transactionComponent = app.getOrThrow(TransactionComponent.class); TransactionHandler txHandler = transactionComponent.createTransactionHandler();
FilmManager and the
ActorManager can be retrieved from the application as shown hereunder:
FilmManager films = app.getOrThrow(FilmManager.class); ActorManager actors = app.getOrThrow(ActorManager.class);
Read more on Speedment transactions here .
Visit Speedment open-source on GitHub and try it out!
Strategies and techniques for building scalable and resilient microservices to refactor a monolithic application step-by-step, a free O'Reilly book . Brought to you in partnership with Lightbend.
java , java 8 , java 9 , speedment , tutorial , database transactions
Published at DZone with permission of Per-Åke Minborg , DZone MVB . See the original article here.
Opinions expressed by DZone contributors are their own.