Tuesday 21 October 2014

Hibernate - How to fix “identifier of an instance altered from X to Y”?

Problem :- Getting the error ” identifier of an instance of com.sample.SampleAltered from 1 to 1″

Solution :- Check whether the java type of the identifier field in the Data Object, the type of the field in the hibernate xml file and the type of the column in the database are compatible types or not.

Explanation :-
This problem will occure only when you have an mismatch of data type between your bean-hibername xml mapping & database table column datatype.

For Example,

class SampleAltered{

long sampleId;
String sampleName;


public int getSampleId(){
….
}

public void setSampleId(int i){
…..
}

}

And this was the hbm file declaration

<class name="com.sample.SampleAltered" table="sample_data">
   <id name=”sampleId” type=”int” column=”sample_id”>
       <generator class=”native” />
   </id>
   <property name=”sampleName” type=”string” column=”sample_name” length=”50″/>
</class>


In above example if you note, class SampleAltered was having sampleId with datatype long & hbm xml file contains the entry for same with datatype int.

Whenever you are trying to do database transaction with above mapping you will get the error of "identifier of an instance altered from X to Y".

To fix this issue you need to change datatype of sampleId either in hbm mapping file or in class.

No comments:

Post a Comment