Home > other >  Can @GenerateValue be used with non primary key attributes?
Can @GenerateValue be used with non primary key attributes?

Time:07-22

I am confused as everywhere it is mentioned to use @GenerateValue only with @Id.

But: can it be used with non primary key attributes?

CodePudding user response:

The JPA specification document provides an important hint that you should not do so, see section 11.1.20, on page 449:

Footnote [110]: Portable applications should not use the GeneratedValue annotation on other persistent fields or properties.

Here, ”other“ refers to fields or properties of an Entity that are not annotated with @Id:

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.

Hence, I would conclude that most, if not all, persistence provider implementations might not support your intended (special) use case.

CodePudding user response:

As per documentation as well as hibernate documentation though this annotation is specifically aimed for simple primary keys (as its elements are used to define primary key generator & strategy), I think you can still use this for non-primary key field provided you are not using any elements of this annotation.

But if you think of using generated value for non-primary key field, fetching records will be slower using this column as your predicate/ where clause.

In that case, you might need to impose index from database. So using GeneratedValue for non-primary key may not be good practice.

  • Related