I have two questions regarding how to create / use the JDO persistence manager (PM, hereafter).
Say, in a Java web application, if I have 10 entities, which can be logically grouped into 2 groups (for example, 5 user related entities and 5 business related entities)
- Should I need two different PMs to manage these 2 groups or only one PM is enough?
- Regarding the initialization, shall I use singleton instance of a PM (which will be shared by all the user's using the app at a given point of time) or should I create a PM for each and every session?
According to the JDO Documentation you create one
PersistenceManagerFactory
per datastore. If you are using JDO to access databases via SQL and you have more than one database, then you will need onePersistenceManagerFactory
per database (since you need to specify the JDBC URL, user name and password when you create thePersistenceManagerFactory
).For simple use cases, you can just create a
PersistenceManager
when you need it and close it in afinally
clause (see the persistence manager documentation).If you use transactions, and the code for updating entities can be spread across multiple methods or objects, I recommend creating the
PersistenceManager
on demand and storing it in aThreadLocal
(or request-scoped object if you use Guice or Spring). This will make sure any code that does updates participates in the current transaction. Make sure to close thePersistenceManager
at the end of the request.If you only need one persistence manager factory, you can do:
Any code that needs a persistence manager can call
Datastore.getPersistenceManager()
Note: I used all static methods to make it simple for the purposes of answering your question. If I was using a dependency-injection framework like Guice, I would make the methods non-static and bind
Datastore
as a Singleton.You could call
finishRequest
in a Servlet Filter: