Home > Java > javaTutorial > Can Hibernate JPA Use Sequences for Non-ID Columns?

Can Hibernate JPA Use Sequences for Non-ID Columns?

DDD
Release: 2024-11-30 20:44:22
Original
693 people have browsed it

Can Hibernate JPA Use Sequences for Non-ID Columns?

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;
}
Copy after login

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!

source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template