Home >Java >javaTutorial >Can Hibernate JPA Generate Sequences for Non-PrimaryKey Columns?

Can Hibernate JPA Generate Sequences for Non-PrimaryKey Columns?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-12-07 08:00:24224browse

Can Hibernate JPA Generate Sequences for Non-PrimaryKey Columns?

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn