File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Object Relational Mapping and the fly likes Session closed exception Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Databases » Object Relational Mapping
Bookmark "Session closed exception" Watch "Session closed exception" New topic

Session closed exception

Kashif Mughal
Ranch Hand

Joined: Jun 19, 2008
Posts: 44

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.



insert is called for both create and update User;

Thanks in Advance,
Cameron Wallace McKenzie
author and cow tipper
Saloon Keeper

Joined: Aug 26, 2006
Posts: 4968

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 J2EE EJB 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.

Kindest regards!

-Cameron McKenzie
Kashif Mughal
Ranch Hand

Joined: Jun 19, 2008
Posts: 44
Hi Cameron

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.

ApplicationContext ---


Which one you reckon is more suitable approach, Why gettting that ClassCastException.
I agree. Here's the link:
subject: Session closed exception
It's not a secret anymore!