Search code examples
javatransactionsjdodatanucleusjdoql

JDO Query inside transactions: yes or no?


I've always used transactions when querying the database, but recently i wondered why.

What are the benefits / drawbacks of using / not using transactions on a "read-only" query?

Transactional:

public int count() {

    PersistenceManager pm=pmf.getPersistenceManager();
    JDOTransaction tx=(JDOTransaction)pm.currentTransaction();

    try{
        tx.begin();
        Query query=pm.newQuery(class);
        query.setResult("count(this)");
        Long count=(Long)query.execute();
        query.closeAll();
        tx.commit();

        return count.intValue();

    }finally{
        if (tx.isActive()) tx.rollback();
        pm.close();
    }
}

Non-transactional:

public int count() {

    PersistenceManager pm=pmf.getPersistenceManager();

    try{
        Query query=pm.newQuery(class);
        query.setResult("count(this)");
        Long count=(Long)query.execute();
        query.closeAll();

        return count.intValue();

    }finally{
        pm.close();
    }
}

What puzzles me is, for example, Datanucleus JDO implementation. if transactions do not lock the objects by default, what's the benefit of such transaction?

From the docs: JDOQL allows control over whether objects found by a query are locked during that transaction so that other transactions can't update them in the meantime: http://www.datanucleus.org/products/accessplatform_2_1/jdo/jdoql.html


Solution

  • That depends. If you have only an atomic read they are probably not needed.

    However, If you want to read more than one value, possibly from different tables, possibly the choice depends on the result of the first query, transactions might help you: You might not want that the database changes while you perform your read-only query. Transactions can provide isolation, such as guaranteeing that the data does not change during the transaction.

    To also mention drawbacks: Transactions are a performance hit.