Hibernate JPA Sequence for Non-Identifier Columns
Question:
Is it possible to generate a sequence-based value for a non-primary key column using Hibernate JPA?
Answer:
No, Hibernate JPA does not directly support generating sequence-based values for non-identifier columns. The @GeneratedValue annotation is only used with @Id to generate auto-numbers.
Workaround:
To achieve this functionality, a workaround is to create a separate entity with a generated Id and a one-to-one relationship with the original entity, as shown below:
@Entity public class GeneralSequenceNumber { @Id @GeneratedValue(...) private Long number; } @Entity public class MyEntity { @Id .. private Long id; @OneToOne(...) private GeneralSequnceNumber myVal; }
In this solution, the GeneralSequenceNumber entity manages the sequence generation, while maintaining a relationship with the original MyEntity.
The above is the detailed content of Can Hibernate JPA Generate Sequences for Non-PrimaryKey Columns?. For more information, please follow other related articles on the PHP Chinese website!