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