Hibernate JPA Sequence for Non-Identifier Column
Question:
Is it feasible to leverage a database sequence to generate values for a table column that is not designated as an identifier or component of a composite identifier using Hibernate JPA?
Answer:
Hibernate JPA does not support automated value generation for properties that are not designated as an identifier. The @GeneratedValue annotation is exclusively used in conjunction with @Id to create auto-incrementing values.
Workaround:
To circumvent this limitation, consider creating a separate entity with a generated identifier, such as:
@Entity public class GeneralSequenceNumber { @Id @GeneratedValue(...) private Long number; } @Entity public class MyEntity { @Id .. private Long id; @OneToOne(...) private GeneralSequnceNumber myVal; }
This approach involves establishing a one-to-one relationship between the main entity and the sequence entity. By leveraging this separate entity, Hibernate can generate the unique sequence value that can be assigned to the desired property in the main entity.
The above is the detailed content of Can Hibernate JPA Use Sequences for Non-ID Columns?. For more information, please follow other related articles on the PHP Chinese website!