0

我在查询数据库时一直使用事务,但最近我想知道为什么。

在“只读”查询中使用/不使用事务有什么好处/缺点?

交易:

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

4

1 回答 1

2

那要看。如果您只有原子读取,则可能不需要它们。

但是,如果您想读取多个值,可能来自不同的表,可能选择取决于第一个查询的结果,事务可能会帮助您: 您可能不希望在执行只读查询时更改数据库. 事务可以提供隔离,例如保证数据在事务期间不发生变化。

还要提到缺点:事务是性能损失。

于 2014-06-07T18:43:13.063 回答