简体   繁体   中英

JPA auto increment on a non primary key field

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM