Wednesday, November 22, 2017

Easily Return Values From a Transaction with Speedment 3.0.17 or Later


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.


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!

No comments:

Post a Comment