Compass in Managed Transactions Environments

Up until now, in order to use Compass, one had to follow the following template:

CompassSession session = compass.openSession();
CompassTransaction tr = null;
try {
    tr = session.beginTransaction();
    // work with Compass session
    tr.commit();
} catch (Exception e) {
    if (tr != null) {
        tr.rollback();
    }
} finally {
    session.close();
}

Compass also came with a simple CompassTemplate class that used the template design pattern in order to simplify the usage. But still, when using Compass within a managed transaction environment, there isn’t really a need for all the Compass managed transaction code, since the transactions are already managed outside of the Compass code. This is the case when working with JTA and CMT, or when using Spring transaction support (either programmatically or declaratively).

Compass already binds its sessions to a transaction, so they are reused when being opened again within the same running transaction. With this new feature Compass tries to automatically join an already running outer transaction. The transaction can be an outer local Compass transaction, a JTA transaction, or a Spring managed transaction. Basically what it means is that if your Compass code already runs in a JTA or a Spring managed transaction, you won’t have to begin a Compass transaction, commit/rollback the transaction, or even close the session. The code ends up looking like this:

// there is already a running transaciton
// (outer local Compass one, JTA, or Spring)
CompassSession session = compass.openSession();
// work with Compass session, no need to call
// beginTransaction or close on the session

This should really simplify Compass usage within a JEE/CMT or Spring environments, and is part of 1.1 M2 SNAPSHOT and beyond. Enjoy!

2 Responses to “Compass in Managed Transactions Environments”

  1. Shane Fitzgibbon Says:

    It seems that this behaviour has been rolled back in M3-SNAPSHOT

    My test case for this functionality started to fail when I upgraded to the latest snapshot and it seems that the following line has been removed from the DefatulCompassSession constructor.

    transactionFactory.tryJoinExistingTransaction(this);

    As a result the checkTransactionStarted in LuceneSearchEngine was failing.

    Is there are reason for removing this functionality and if so what is the template for compass usage now?

  2. Shane Fitzgibbon Says:

    Ignore that last comment. We were looking at an older version of Compass believing that we were looking at a recent M3-SNAPSHOT.

    Sorry about any confusion.

Leave a Reply

XHTML: You can use these tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <code> <em> <i> <strike> <strong>