views:

50

answers:

1

Does a persistence manager generally need to be closed? Can you just keep one open and re-use it all the time, ie just repeat this pattern:

Transaction tx = pm.currentTransaction();
try {
    tx.begin();
    // do stuff
    tx.commit();
} finally {
    if (tx.isActive()) tx.rollback();
}

What are the downsides of this? It seems to make sense as you would never need to 'detatch' objects due to the persistence manager being closed?

+1  A: 

You can keep it open all the time if you want. The main issue to consider is when you are running 'update' queries, how quickly do you want the changes to take effect. Closing the persistence manager persists these changes immediately, whereas not doing do explicitly will rely upon the datastore do persist your changes at its own convenience. If you are using transactions, this is irrelevant. Aside from that, there's not really any downside. There's a large cpu + time overhead upon the very first initialization of the PM (first use after you deploy), but after that opening/closing the PM is basically free.

Travis J Webb
Is there any way to force the pm to persist the data, besides closing it or committing a transaction?
Peter Recore
Yes you can also do a flush() I think, however why not just use transactions?
Jacob