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.
Asked
Active
Viewed 41 times
1
-
2I'm not sure if you cant, but i'm sure that you shouldn't. Your mapping must reflect your database. – AndreDuarte Jul 10 '15 at 15:04
2 Answers
1
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.

Dragan Bozanovic
- 23,102
- 5
- 43
- 110
0
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.