java - How to use JDO persistence manager? -
i have 2 questions regarding how create / use jdo persistence manager (pm, hereafter).
say, in java web application, if have 10 entities, can logically grouped 2 groups (for example, 5 user related entities , 5 business related entities)
- should need 2 different pms manage these 2 groups or 1 pm enough?
- regarding initialization, shall use singleton instance of pm (which shared user's using app @ given point of time) or should create pm each , every session?
according jdo documentation create 1 persistencemanagerfactory
per datastore. if using jdo access databases via sql , have more 1 database, need 1 persistencemanagerfactory
per database (since need specify jdbc url, user name , password when create persistencemanagerfactory
).
for simple use cases, can create persistencemanager
when need , close in finally
clause (see the persistence manager documentation).
if use transactions, , code updating entities can spread across multiple methods or objects, recommend creating persistencemanager
on demand , storing in threadlocal
(or request-scoped object if use guice or spring). make sure code updates participates in current transaction. make sure close persistencemanager
@ end of request.
if need 1 persistence manager factory, can do:
public class datastore { private static persistencemanagerfactory pmf; private static final threadlocal<persistencemanager> per_thread_pm = new threadlocal<persistencemanager>(); public static void initialize() { if (pmf != null) { throw new illegalstateexception("initialize() called"); } pmf = jdohelper.getpersistencemanagerfactory("jdo.properties"); } public static persistencemanager getpersistencemanager() { persistencemanager pm = per_thread_pm.get(); if (pm == null) { pm = pmf.getpersistencemanager(); per_thread_pm.set(pm); } return pm; } public static void finishrequest() { persistencemanager pm = per_thread_pm.get(); if (pm != null) { per_thread_pm.remove(); transaction tx = pm.currenttransaction(); if (tx.isactive()) { tx.rollback(); } pm.close(); } } }
any code needs persistence manager can call datastore.getpersistencemanager()
note: used static methods make simple purposes of answering question. if using dependency-injection framework guice, make methods non-static , bind datastore
singleton.
you call finishrequest
in servlet filter:
public class persistencemanagerfilter implements javax.servlet.filter { public init(filterconfig filterconfig) { datastore.initialize(); } public void dofilter(servletrequest request, servletresponse response, filterchain chain) throws ioexception, servletexception { try { chain.dofilter(request, response); } { datastore.finishrequest(); } } }
Comments
Post a Comment