I'm currently using JUnit to test various things with my Hibernate application. Basically, in my junit setup and teardown methods, I insert everything into the database and delete everything from the database, respectively. And in each of the tests I test various things. When I run the first test, everything (the insertions, the test, and the deletions) run smoothly; however, when the setup method is called a second time to run the second test, I get the following error:
Code:
Exception: a different object with the same identifier value was already associated with the session
Here is the code for my setup function:
Code:
try{
session = HibernateUtil.currentSession();
tx = session.beginTransaction();
// save instances in session
partner1_Id = (String) session.save(partner1);
pooAddress1_Id = (String) session.save(pooAddress1);
poaAddress1_Id = (String) session.save(poaAddress1);
............
// commit transaction
tx.commit();
}
catch( Exception e ){
System.out.println("Exception: " + e.getMessage() );
try{
if( tx != null )
tx.rollback();
}
catch(HibernateException he1 ){
System.out.println("Hibernate Exception: " + he1.getMessage());
}
}
finally{
try{
HibernateUtil.closeSession();
}catch( HibernateException he ){
System.out.println( "HibernateException " + he.getMessage() );
}
}
Likewise, here is the code for my teardown function:
Code:
try{
session = HibernateUtil.currentSession();
tx = session.beginTransaction();
// delete instances from session
session.delete(partner1);
session.delete(pooAddress1);
session.delete(poaAddress1);
...............
//commit to database
tx.commit();
}
catch( Exception e ){
System.out.println("Exception: " + e.getMessage() );
try{
if( tx != null )
tx.rollback();
}
catch(HibernateException he1 ){
System.out.println("Hibernate Exception: " + he1.getMessage());
}
}
finally{
try{
HibernateUtil.closeSession();
}catch( HibernateException he ){
System.out.println( "HibernateException " + he.getMessage() );
}
}
I have read and searched for the forum, and I found one potential error could be because cascade=all; however, for all my associations, I have cascade=none.
Plus, when I remove the HibernateUtil.closeSession() from the finally block in the setup method, everything works fine, and I don't know why that is the case either?
I'd appreciate any help - why I receive this error or why it works fine when I remove the closeSession() statement from the setup method. I'm confused.
Thanks in advance.