org.hibernate.HibernateException: identifier of an instance
of org.cometd.hibernate.User altered from 12 to 3
in fact, my user
table
In my particular case, this was caused by a method in my service implementation that needed the spring @Transactional(readOnly = true)
annotation. Once I added that, the issue was resolved. Unusual though, it was just a select statement.
If you are using Spring MVC or Spring Boot try to avoid: @ModelAttribute("user") in one controoler, and in other controller model.addAttribute("user", userRepository.findOne(someId);
This situation can produce such error.
In my case, I solved it changing the @Id field type from long to Long.
Also ran into this error message, but the root cause was of a different flavor from those referenced in the other answers here.
Generic answer: Make sure that once hibernate loads an entity, no code changes the primary key value in that object in any way. When hibernate flushes all changes back to the database, it throws this exception because the primary key changed. If you don't do it explicitly, look for places where this may happen unintentionally, perhaps on related entities that only have LAZY loading configured.
In my case, I am using a mapping framework (MapStruct) to update an entity. In the process, also other referenced entities were being updates as mapping frameworks tend to do that by default. I was later replacing the original entity with new one (in DB terms, changed the value of the foreign key to reference a different row in the related table), the primary key of the previously-referenced entity was already updated, and hibernate attempted to persist this update on flush.
This is an old question, but I'm going to add the fix for my particular issue (Spring Boot, JPA using Hibernate, SQL Server 2014) since it doesn't exactly match the other answers included here:
I had a foreign key, e.g. my_id = '12345', but the value in the referenced column was my_id = '12345 '. It had an extra space at the end which hibernate didn't like. I removed the space, fixed the part of my code that was allowing this extra space, and everything works fine.
Faced the same Issue. I had an assosciation between 2 beans. In bean A I had defined the variable type as Integer and in bean B I had defined the same variable as Long. I changed both of them to Integer. This solved my issue.