Should a Guice-Injected DAO be Singletons?

I am currently working on an application using Guice / JPA / Hibernate to retrieve information from my database.

I read Guice docs about working with JPA and EntityManagars here: http://code.google.com/p/google-guice/wiki/JPA ,

But I had trouble understanding when I have to make my singleton for DAO implementation.

I read this question in S / O regarding the use of Spring DAO, where it says:

Creating a DAO instance for each request will be insane.

Does this carry over for DI containers other than Spring? If I insert a DAO provider in my servlet and call when necessary, should the implementation of the DAO service be Singleton?

Here is a basic outline of one of my DAOs:

public DAOImpl implements DAOService { <-- SHOULD THIS BE ANNOTATED @Singleton? @Inject private EntityManager em; // OR // @Inject // private Provider<EntityManager> emProvider - If it 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 what is it 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.

+4
source share
2 answers

No, because the EntityManager is absolutely not thread protected. You need to use suppliers.

+5
source

Yes, the DAO must be Singletons, but the EntityManager must be obtained through the provider.

0
source

Source: https://habr.com/ru/post/1399471/


All Articles