Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

In Hibernate 5.1.0 / JPA 2.1, is there any way to merge based on a unique key instead of based on a primary key?

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

I'd like to be able to call EntityManager#merge(entity) and, if the primary key of entity isn't null, have Hibernate / JPA use the primary key to merge, but, if the primary key is null, use the unique key to merge (i.e. if the primary 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, then a new row will be inserted).

like image 578
XDR Avatar asked Mar 09 '16 20:03

XDR


1 Answers

By definition - that is the JPA specification¹ document aka JSR 338 - there is no way to annotate the desired behaviour which in essence can be reduced to:

if the primary key of entity isn't null, have Hibernate / JPA use the primary key to merge, but, if the primary key is null, use the unique key to merge

onto an @Entity class.

Sadly, there won't be a real solution for this requirement unless this idea is formulated as a feature request for the next major JPA specification release. In 2019, however, it is highly unlikely² that there will be an attempt to draft a JPA specification in version 2.3 or even 3 any time soon.

Nevertheless, feel free to propose a feature request at the JPA-API Github project maintained by the Eclipse foundation.

Hope it helps.

Footnotes

¹ In version 2.2 or the previous version 2.1/2.0

² See time chart at https://projects.eclipse.org/projects/ee4j.jpa and the low volume of activity at the corresponding mailing list.

like image 153
MWiesner Avatar answered Sep 19 '22 15:09

MWiesner