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?

naXa stands with Ukraine
  • 35,493
  • 19
  • 190
  • 259
Ido Barash
  • 4,856
  • 11
  • 41
  • 78

2 Answers2

9

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

Johanneke
  • 5,443
  • 4
  • 20
  • 33
  • 2
    And you also need to set nullable=false, as it is implied by Hibernate's NatuarlId – Manu Jan 26 '15 at 20:22
  • 2
    This will not replace an @Id column. Petr's answer is correct. – Alkanshel Aug 10 '16 at 20:56
  • @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. – Johanneke Aug 12 '16 at 09:21
  • @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. – maaartinus Feb 27 '17 at 19:09
6

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

Petr Mensik
  • 26,874
  • 17
  • 90
  • 115