Hibernate :session and begin transaction in the constructor of the abstractDao
posted 8 years ago
I wanted to know your thoughts on this one. We are using a genericDao. All Dao's used as part of the application will inherit this genericDao. I was trying to modularize as much code as possible in this generic dao.
In the constructor of the genericDao I am planning to keep the fetch session and begin transaction calls.
session = HibernateUtil.currentSession(user);
tx = session.beginTransaction();
Subsequent method calls incepting from the derived dao's will touch upon this constructor as part of normal inheritance flow and the session/transaction attributes required by these methods will be set in an implicit manner. The benefit is I don't have to write these lines in each of the methods in the genericDao (save, saveUpdate, getXXX, finders etc).
Do you feel there is any potential downside to this approach.
Let me know
well,nowadays you don't have to do your transaction management yourself. Transaction management is typically a cross cutting concern
that you don't want to do in your code but let the application server or spring handle.
With spring for instance, we just put @Transactional above our method and case closed and in EJB, the container handles everything.
Anyway, and don't really see how starting a transaction in the constructor of the dao will have any influence on the getters and setters.
You'll probably get it working but I think your solution it is a bit outdated.