多个数据存储区操作 - 我们需要多少持久性管理器参考?

时间:2010-07-19 15:44:46

标签: java google-app-engine

我想运行一些数据存储操作,但我不确定是否需要为每个操作获得对持久性管理器的新引用(我认为这很昂贵?)。例如:

public void submitUserRating(String username, String productId, int val) {

    PersistenceManagerFactory pmf = PMF.get();
    PersistenceManager pm = pmf.getPersistenceManager();

    Transaction tx = pm.currentTransaction();
    try {

        // Operation 1, don't care if this fails.
        try {
            Rating rating = new Rating(username, val);
            pm.makePersistent(rating);
        } catch (Exception ex) {
            // no big deal, carry on.
        }

        // Operation 2...
        // Operation 3...
        // Operation N...
        // all on same pm, ok?

        // Do transaction, ok to do on same pm reference still?
        tx.begin();
        try {
            Product product = pm.getObjectById(productId);
            product.setNumViews(product.getNumViews() + 1);
            pm.makePersistent(product);
        } catch (Exception ex) {}
        }
        tx.commit();
    }
    finally {
        if (tx.isActive()) {
            tx.rollback();
        }
        pm.close();
    }
}

以上只是一个例子。我认为这可行,但如果我们想做两笔交易怎么办?:

public void myexample() {


    PersistenceManagerFactory pmf = PMF.get();
    PersistenceManager pm = pmf.getPersistenceManager();

    Transaction tx = pm.currentTransaction();
    try {
        // Transaction operation 1
        tx.begin();
        pm.makePersistent(new Blah());
        tx.commit();

        // Transaction operation 2
        tx.begin();
        pm.makePersistent(new Foo());
        tx.commit();
    }
    finally {
        if (tx.isActive()) {
            tx.rollback();
        }
        pm.close();
    }
}

在上面,操作1& 2是独立的 - 换句话说,我不在乎op1是否失败,我想继续并执行op2。

由于

1 个答案:

答案 0 :(得分:1)

您只需要一个PersistenceManager。