Core Java

Easily Return Values From a Transaction with Speedment 3.0.17 or Later

Transactions

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 artist 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 likes. Here is how it might look like:

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 boiler plate code, we can express functions that are to be performed within transactions using Speedment.

Preparations

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

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

TheFilmManager 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!

Published on Java Code Geeks with permission by Per Minborg, partner at our JCG program. See the original article here: Easily Return Values From a Transaction with Speedment 3.0.17 or Later

Opinions expressed by Java Code Geeks contributors are their own.

Per Minborg

I am a guy living in Palo Alto, California, but I am originally from Sweden. I am working as CTO on Speedment with Java and database application acceleration. Check it out on www.speedment.com
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Back to top button