JPA equivalent to Hibernate's @NaturalId
Asked Answered
C

2

13

In Hibernate I can create a unique key using @NaturalId on several properties of the entity.

Is there a JPA equivalent annotation, something that is a part of javax.persistence?

Craniate answered 10/1, 2013 at 9:0 Comment(0)
A
9

What I usually do is add a unique constraint on the columns, using @Table(uniqueConstraints = @UniqueConstraint(columnNames={column_1, ..., column_n}))

Aeriell answered 14/6, 2013 at 8:58 Comment(4)
And you also need to set nullable=false, as it is implied by Hibernate's NatuarlIdWilser
This will not replace an @Id column. Petr's answer is correct.Overcapitalize
@Amalgovinus The question implied that the desired solution should create a unique key. It was not necessary to mimic the workings of the NaturalId annotation exactly. My answer clearly states that I add unique constraints to columns, I don't pretend I am replacing the NaturalId annotation.Aeriell
@Amalgovinus I'm using @NaturalId as a "secondary" id, together with @Id Integer id. @NaturalId really like an unique constraints together with NOT NULL and I doubt, it can be used as primary id.Intumescence
D
6

No, there is not. You will have to use composite keys, so either EmbeddedId or IdClass depending what you prefer.

Dismember answered 10/1, 2013 at 9:6 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.