Over a million developers have joined DZone.

Easily Return Values From a Transaction With Speedment

DZone's Guide to

Easily Return Values From a Transaction With Speedment

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.

· Java Zone
Free Resource

Download Microservices for Java Developers: A hands-on introduction to frameworks and containers. Brought to you in partnership with Red Hat.

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.

Returning Transaction Values

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();

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

What's Next?

Visit Speedment open-source on GitHub and try it out!

Download Building Reactive Microservices in Java: Asynchronous and Event-Based Application Design. Brought to you in partnership with Red Hat

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.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}