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).
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 isnull
, 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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With