I am currently working on an application utilizing Guice / JPA / Hibernate to get info from my database.
I have read the Guice docs on working with JPA and EntityManagars here: http://code.google.com/p/google-guice/wiki/JPA,
But I am having trouble understanding when I should make my DAO Implementations Singletons.
I have read this question on S/O regarding Spring's use of DAO's where it says:
Instantiating a DAO for every request would be crazy.
Does that carry over for DI containers other than Spring? If I am injecting a DAO Provider into my Servlet and calling when needed, should the DAO Service Implementation be a Singleton?
Here is a basic outline of one of my DAO's:
public DAOImpl implements DAOService { <-- SHOULD THIS BE ANNOTATED @Singleton?
@Inject
private EntityManager em;
// OR
// @Inject
// private Provider<EntityManager> emProvider - If it's a singleton.
@Inject
DAOImpl(OtherServices os) {
this.otherServices = os;
}
@Transactional
public MyPersistedObject getPersistedObject(long id) {
MyPersistedObject mpo = em.find(MyPersistedObject.class, id);
return mpo;
}
}
And how it's called:
@Singleton
public MyServlet(HttpRequest req, HttpRequest res)
extends ServletInterfaceOfTheDay {
private final daoService; // If Singleton
// OR
// private final Provider<DAOService>; If Instanced DAO
@Inject
MyServlet(DAOService dao) {
this.daoService = dao;
}
// Gather Information from request here...
MyPersistedObject mpo = daoService.getPersistedObject(requestIdInfo);
// OR daoService.get().getPersistedObject(requestIdInfo);
// Process Response Info here....
}
Thanks for the help.
No, since EntityManager is absolutely not Thread-safe. You need to use providers.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With