Reputation: 4470
In JPA or Hibernate, is it possible to merge a new entity (that does not have a primary key value) into a persistence context based on a unique key other than the primary key?
Or is all JPA / Hibernate merging only performed on primary keys?
If this isn't possible with a simple method call, are my only options to either:
@UniqueConstraint
annotations, and searches for existing entities based on the the attributes in the @UniqueConstraint
s. I'd try to merge into the first entity that was found for any of the @UniqueConstraint
s. If no matches, then I could just persist the new entity.Upvotes: 2
Views: 1513
Reputation: 153700
Hibernate only requires a unique key for the @Id
property, and, although typically the primary key is used for this purpose, you can use any unique key for the @Id
property.
More, you can use a primary key for the @Id
property and a unique key as the @NaturalId
. You can fetch the entity by its natural-id and then merge it in a different Session
because merging takes an entity and not an identifier.
Upvotes: 0