Win a copy of Re-engineering Legacy Software this week in the Refactoring forum
or Docker in Action in the Cloud/Virtualization forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Session closed exception

 
Kashif Mughal
Ranch Hand
Posts: 44
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi

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.

Tests



DAO



insert is called for both create and update User;
 
Cameron Wallace McKenzie
author and cow tipper
Saloon Keeper
Posts: 4968
1
Hibernate Spring Tomcat Server
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 44
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.

ApplicationContext---

DAOFactory---


Secondly, instead of wiring the SessionFactory into the GenericDAOImpl, I have to wire it seperately for each bean like this.

ApplicationContext ---


DAOFactory---


Which one you reckon is more suitable approach, Why gettting that ClassCastException.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic