tags:

views:

508

answers:

3

Is there ever a case in a standard webapp where one would pass an EntityManager or Session as a parameter to a DAO call, i.e. findPersonByName(String name, Session session)? Or should the the opening and closing of the session be abstracted in the implementation?

A: 

No, it should never be used, but a Service layer might. Imagine you have two different methods (in possibly different DAO's) that need to be encapsulated in the same transaction (commit/rollback), than you might want/have to use the same connection object.

A: 

No, neither the DAO nor the service layers should know or care about session. Services ought to be idempotent. The session is an view/controller artifact; let the controller manage it.

duffymo
+4  A: 

A better approach would be to initialize or otherwise inject the DAO with the SessionFactory. Then you can do things like this:

public abstract class AbstractHibernateDao<T extends Object>
    implements AbstractDao<T> {

    private SessionFactory sessionFactory;

    public void setSessionFactory(SessionFactory sessionFactory) {
        this.sessionFactory = sessionFactory;
    }

    protected Session getSession() {
        return sessionFactory.getCurrentSession();
    }

    public void save(T t) { getSession().save(t); }

    public void update(T t) { getSession().update(t); }

    ...
}

without having to pass Sessions all over the place.

Willie Wheeler
Yes, I was planning on using an `EntityManagerFactory`. Was just wondering if there ever was a case where an `EntityManager` would be initialized and passed in outside the service. Also, with the `getSession()` method, where/when is the current session initalized?
jtgameover
Well, it's hard to say "never," but that's what I want to say. The standard practice is for the service to encapsulate transaction management, and session boilerplate (opening/closing, etc.) typically happens in the context of transaction management... [more]
Willie Wheeler
There are a couple of approaches here. One would be to use some kind of proxying mechanism (e.g. Spring offers TransactionManagers of different sorts) to wrap your service beans in a transparent way. The TransactionManager knows about the factory and handles session init. [more]
Willie Wheeler
The other one would be to simply handle transaction management and session management yourself, but behind the service interface itself, not by accepting sessions as service method args.Hope that helps.
Willie Wheeler