Jadiel de Armas
Jadiel de Armas

Reputation: 8802

Can I map a field @Id when it is not the id in the database?

I have a database table that has three fields: two of them are a composite key for the table, and the other one is an autogenerated field that is not the id of the table. When mapping this table to a JPA entity, can I map the autogenerated field as the @Id, even when it is not? If yes, what are the implications? Note: I cannot change the database.

Upvotes: 1

Views: 64

Answers (2)

Dragan Bozanovic
Dragan Bozanovic

Reputation: 23562

Yes, you can. This is actually often the case when a Hibernate entity is mapped to a database view which is defined on top of multiple real tables (and other views).

If you don't intend to create new instances of that entity through Hibernate, then there are no implications (if the key is really unique of course).

If you will be persisting new instances with Hibernate, then be sure to pick the appropriate identifier generation strategy.

Upvotes: 1

6ton
6ton

Reputation: 4214

You should not - @Id has special meaning and will be used as the primary key by hibernate.

The @GeneratedValue annotation works only if @Id is also present, so you cannot use that on the non-id field. More details here - there are possible alternatives depending on which db you are using.

Upvotes: 0

Related Questions