Reputation: 11
Is it possible to auto-increment a JPA field which is not a PrimaryKey?
I already saw something like creating a new entity with only an id which is auto incremented and to use it on my wanted field, but I have no clue how to make it.
Upvotes: 1
Views: 2406
Reputation: 30007
No, unfortunately the @GeneratedValue
annotation can only be used on a primary key field.
From the docs
The GeneratedValue annotation may be applied to a primary key property or field of an entity or mapped superclass in conjunction with the
Id
annotation. The use of the GeneratedValue annotation is only required to be supported for simple primary keys. Use of the GeneratedValue annotation is not supported for derived primary keys.
I'm not sure what you want to do, but alternatively, you can have a native query that gets the next value from a sequence, and set that value in your field. I do think that whatever you're trying to do, there will be another approach that doesn't use a sequence... if you share the problem other people might be able to suggest solutions.
Upvotes: 2