Hibernate how to prevent duplicate entry with generated id

serenitytr picture serenitytr · Mar 24, 2011 · Viewed 7.3k times · Source

Is there a way to prevent duplicate data entry with hibernate on entities that have auto generated primary key?

To be more specific, i have a persistent object in the database and have a transient object (not inserted to the database yet) and those two objects are same with respect to equals and hashcode methods. But, since the id of the entity class of those objects is annotated with generated value annotation, hibernate still creates a new instance for the transient object in the database. As a result the database has duplicate entries (with respect to equals and hashcode methods) with different primary keys.

Yes, I know if I make the PK not auto generated, of if I use UUID, then i would achieve my goal. But I just wanna ask why equals and hashcode methods do not work for the entities with auto generated primary key? Or am i doing something wrong?

Answer

axtavt picture axtavt · Mar 24, 2011

why equals and hashcode methods do not work

Hibernate doesn't respect equals()/hashCode() here, because there are no efficient ways to do so.

How can Hibernate check that object with the same identity (in terms of equals()) already exists in the database? Since equals() can contain arbitrary conditions, Hibernate can't turn it into SQL query, so that the only way to check it is to load all objects into memory and call equals() on them to compare them with the object you are going to save.

Therefore Hibernate uses primary keys to define objects' identity.

Or am i doing something wrong?

It's not clear what are you going to achieve. If you want Hibernate to update objects in the database with the state of objects you pass in, you need to use merge().

See also: