5

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.

Community
  • 1
  • 1
oberger
  • 1,217
  • 2
  • 16
  • 31

2 Answers2

5

No, since EntityManager is absolutely not Thread-safe. You need to use providers.

DwB
  • 37,124
  • 11
  • 56
  • 82
Guillaume Polet
  • 47,259
  • 4
  • 83
  • 117
  • So use an instanced DAOImpl through the provider to the servlet? Is that overkill? Is my pattern wrong? – oberger Mar 02 '12 at 22:19
  • No, it looks fine to me. Just use providers and you are good to go. I suppose that you are using PersistFilter and JpaPersistModule, right (I am not completely sure about the exactness of the names)? Alternatively, you could choose to use a Provider in your DAO, that would work fine too. You can the Singleton your DAO – Guillaume Polet Mar 02 '12 at 22:28
  • JpaPersistModule yes, but no PersistFilter, I edited my question to include my use of @Transactional. – oberger Mar 02 '12 at 23:36
0

Yes, DAOs should be Singletons, but EntityManager must be retrieved through a provider.

Jamol
  • 2,281
  • 2
  • 28
  • 28