This week's book giveaway is in the OCAJP 8 forum. We're giving away four copies of OCA Java SE 8 Programmer I Study Guide and have Edward Finegan & Robert Liguori on-line! See this thread for details.
I am new to hibernate tech, I am testing the DAO and for each CRUD method I am opening and closing the hibernate session in DAO. But it goes fine for the first time but after that it gives me Session is Close! exception. I cant figure out why.
Its breaking the tests, My Code is as follow; Your quick reply will be appreciated.
I am opening and closing the hibernate session in DAO
Well, it looks like you've walked head first into an anti-pattern. This is often referred to as the transaction per method call, or transaction per interaction anti-pattern. It's common in many J2EEEJB 2.x applications, but the trend is very much away from this.
You really should think of allowing the client application to manage transaction demarcation, and thus, the opening and closing of the session. This allows many database calls to occur within a single transaction, rather than opening and closing them constantly. Plus, you won't be able to allow multiple DAO calls to act as a single unit of work, as each DAO uses its own Session/transaction. That's a HUGE problem!
Take a look at the open session per view design construct. It will help you out greatly, and help you avoid many potential LazyInitializationExceptions and such.
Joined: Jun 19, 2008
Thanks a lot for your time, I appreciate your suggestion. I have got another situation which you might be the right to discuss; I am creating DAO using DAOFactory as mentioned Hibernate DAO ref.
Also I am trying to fit this with HibernateDaoSupport from Spring Framework, There are two ways I can try to wire SessionFactory into DAO.
Firstly, In the ApplicationContext.xml I am wiring the SessionFactory into GenericDAOImpl. I am getting the java class cast exception.
Secondly, instead of wiring the SessionFactory into the GenericDAOImpl, I have to wire it seperately for each bean like this.