Is there a way to combine a JPA entity based on a unique key instead of a primary key (in Hibernate)?

In Hibernate 5.1.0 / JPA 2.1, is there a way to merge based on a unique key, and not based on a primary key?

I have values ​​for a unique key as input from an external system, but the input does not explicitly contain my internal primary key.

I would like to be able to call EntityManager#merge(entity) , and if the primary key of the entity not null, use Hibernate / JPA to merge the primary key, but if the primary key is zero, use a unique key to merge (i.e. if the primary the object is null, and if the unique key corresponds to a row in the database, the row will be updated, but if there is no row in the database corresponding to the unique key, a new row will be inserted).

+5
source share
1 answer

By definition, this is the JPA specification - a document also known as JSR 338 - there is no way to annotate the desired behavior, which essentially can be shortened to:

if the primary key of the entity is not null , Hibernate / JPA uses the primary key to merge, but if the primary key is null , use a unique key to merge

to the @Entity class.

Unfortunately, there will be no real solution to this requirement unless this idea is formulated as a function request for the next major release of the JPA specification. However, in 2019 it is highly unlikely that an attempt will be made in the near future to draft the JPA specification in version 2.3 or even 3.

However, feel free to suggest a feature request in the Github JPA-API project supported by the Eclipse Foundation.

Hope it helps.

Footnotes

Version In version 2.2 or previous version 2.1 / 2.0

Β² See the schedule at https://projects.eclipse.org/projects/ee4j.jpa and the low activity level on the corresponding mailing list.

0
source

Source: https://habr.com/ru/post/1244764/


All Articles