views:

19

answers:

0

Hi,

I'd like to run a few datastore operations, but am not sure if we need to get a new reference to the persistence manager for each operation (I think this is expensive?). Example:

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();
    }
}

the above is just an example. I think that could work, but what if we want to do two transactions?:

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();
    }
}

In the above, operation 1 & 2 are independent - in other words, I don't care if op1 fails, I'd like to continue on and perform op2.

Thanks