NonUniqueObjectException: a different object with the same identifier value was already associated with the session

The error different object with the same identifier value was already associated with the session would happen quite sometime while working on hibernate with java web application

It occurs when the hibernate session contains object to be updated and when the application tries to update another object with the same id as that of the session owned one.

Let’s assume there is an object Can with properties material and volume as follows for simple illustration


public class Can{
  private Integer canId;
  private String material;
  private Double volume;
  //getters; setters;
}

Assume we have DAO for this object named CanDao.

So, being on your jsf dataTable you selected one ‘can’ object to be updated or deleted. I just put the CanDao object directly into the Bean for the illustration purpose – it is good to wrap this object in the service object, say CanService, for easier manupulation.

Lets have the bean as follows:


class CanBean{
   private HtmlDataTable canTable; //for binding list of can objects from jsf list
   private CanDao canDao; //dao object;
   private List cans; //list jsf datatable would use it.
   .
   .
   .
   public String update(){
      //get the selected object from data table
      ICan selectedCan = (ICan)this.canTable.getRowData();
      this.canDao.saveOrUpdate(selectdCan);
      return "Update";
   }
}

Here the line calling saveOrUpdate would be responsible for throwing the error of different object with the same identifier value was already associated with the session

Here is how to fix it
Since the session contain the same identifier, let’s get the actual or original object from the session it self


  //corrected update method for Can Bean
   public String update(){
      //get the selected object from data table
      ICan selectedCan = (ICan)this.canTable.getRowData();
      ICan original = this.canDao.getById(selectedCan.getCanId()); //
      original.setVolume(selectedCan.getVolume());      
      original.setMaterial(selectedCan.getMaterial());
      this.canDao.saveOrUpdate(original);
      return "Update";
   }

This would fix the problem. But, there are other ways of preventing the session problem from occurring – googling a bit might help.

If you are J2EE developer:

Hello world with maven step by step

See how you can add session bean

Why do I get can not forward after response error and how to solve it