Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Should Guice-Injected DAO's be Singletons?

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.

like image 556
oberger Avatar asked Mar 02 '12 22:03

oberger


1 Answers

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

like image 111
Guillaume Polet Avatar answered Oct 12 '22 06:10

Guillaume Polet