我在查询数据库时一直使用事务,但最近我想知道为什么。
在“只读”查询中使用/不使用事务有什么好处/缺点?
交易:
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();
}
}
非交易:
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();
}
}
令我困惑的是,例如,Datanucleus JDO 的实现。如果事务默认不锁定对象,那么这样的事务有什么好处?
来自文档:JDOQL 允许控制查询找到的对象是否在该事务期间被锁定,以便其他事务同时无法更新它们:http://www.datanucleus.org/products/accessplatform_2_1/jdo/jdoql。 html