I am using hibernate in my project and it is well going, but my problem is i am little bit confused that is i am going good way for writing hibernate functions. Below i paste my block of code to understand how i had written the hibernate functions please check it and tell me whther it is a correct method. Here is my structure of block code
SessionFactory sessionFactory =
(SessionFactory) ServletActionContext.getServletContext().getAttribute(HibernateListener.KEY_NAME);
Session hibernatesession = sessionFactory.openSession();
try {
hibernatesession.beginTransaction();
// my database access will be here
hibernatesession.getTransaction().commit();
hibernatesession.flush();
}
catch(Exception e){
hibernatesession.getTransaction().rollback();
e.printStackTrace();
}finally{
hibernatesession.close();
}
This is the structure that i have created for all my dao class functions, but now my website is loading very slowly. So my questions is the stricture i have used is a correct one. Is the above code causes to open multiple session hibernate at a time.
It is not good design to do transaction management in a DAO class. I would warmly recommend using Spring and its declarative transaction management, which is a breeze to set up and a no-brainer to use. If that is not available to you, then you should at least make a poor man’s alternative. One suggestion is to make each DAO a subclass of a class that has a method that does the boilerplate part (session open/close, transaction begin/commit) and calls out to an overridable method to do the real work. This would implement the Template pattern for your scenario. This is an outline:
Another suggestion, and something I actually used on a project ten years ago, is to implement the Strategy pattern. In that case you’d pass an object to
executethat implements the methoddoTheRealStuff. Also, in that case theDaoTemplateclass could be a singleton (a different name for the class would be appropriate then).