XDR
XDR

Reputation: 4470

Merging in JPA / Hibernate based on unique key instead of primary key

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:

  1. replace the existing primary key with the unique key
  2. write code that finds any existing entity using the values of the attributes in the unique key. If I were to do this, I guess I'd write a static method that looks for @UniqueConstraint annotations, and searches for existing entities based on the the attributes in the @UniqueConstraints. I'd try to merge into the first entity that was found for any of the @UniqueConstraints. If no matches, then I could just persist the new entity.

Upvotes: 2

Views: 1513

Answers (1)

Vlad Mihalcea
Vlad Mihalcea

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

Related Questions