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

different obj with the same identifier was already associated with hibernate session

 
Dhaval P Patel
Greenhorn
Posts: 2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,

I am using following code to update SolutionCategory,
simple update without validation is working fine.....


public void update(SolutionCategory o, Errors e) throws ServiceValidationException {

SolutionCategory solutionCategory = (SolutionCategory) o;
DynamicCriteria dynaCrit = new DynamicCriteria();
dynaCrit.add("name",solutionCategory.getName(),DynamicCriteria.EQUAL);
List list = findAll(dynaCrit);

SolutionCategory tempSC = (SolutionCategory) list.get(0);
if(list.size() > 0 && !tempSC.getID().equals(o.getID()) ){
e.reject("DUPLICATE_CATEGORY_NAME");
throw new ServiceValidationException(e);
}

dao.update(solutionCategory);
}


Before updating the record I want to validate duplicate SolutionCategory Name.
So to implement that stuff I am going to fetch all record by :- List list = findAll(dynaCrit); method.

Now after this validation code while executing dao.update(solutionCategory); line my hibernate session has two different object with the same identifier value i). Original Object of the Update function
ii). another one is found by findAll method

Because of this two object, at time of saving record following error has been generate by hibernate.

a different object with the same identifier value was already associated with the session: [com..cs.solutionreg.solutioncategory.SolutionCategory#12]; nested exception is org.hibernate.NonUniqueObjectException: a different object with the same identifier value was already associated with the session: [com.cs.solutionreg.solutioncategory.SolutionCategory#12]

Could you give me proper solution?

i). How I detach extra Object form Hibernate Session ??
ii). Should not use this kind of validation in update function ??
 
Mark Spritzler
ranger
Sheriff
Posts: 17278
6
IntelliJ IDE Mac Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
If you load to check for duplicate data, then I suggest evicting it from the Session before you get to the update statement, so that it is no longer in the session.

Personally, I would not even do that query and let the update go through, but just put a unique constraint on the name field, and let an exception be thrown when a duplicate name is used. Either way, you have an "exception" in validation and will have to close the Session anyway and go back to the user with the "error"

Mark
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic