Home > Software design >  Postgresql Spring Data @GeneratedValue without @Id return null value
Postgresql Spring Data @GeneratedValue without @Id return null value

Time:06-25

im working in spring boot project i want to map a property with serial (using my sequence) column in my table and this column is not the ID. i found this solution :

  @Column(name = "DEMANDE_NUMBER", insertable = false, updatable = false, columnDefinition = "serial")
  private Integer demandeNumber;

(because @GeneratedValue persist null and doesn't use the sequence)

this solution works fine and the field is persisted in my DB and the value uses the sequence but when i get my object after saving using my repository the demandeNumber is null

    Demande savedDemande= demandeRepository.save(demandeToSave);
   //demandeObj .getDemandeNumber() return null

any suggestion to resolve this issue please ?

Thanks.

CodePudding user response:

according to this answer How to use a sequence generator for a non ID field?

i added the following annotation on my property

  @Generated(GenerationTime.INSERT)
  @Column(name = "column_name", columnDefinition = "serial", updatable = false)

you should import the package from hibernate and not javax.persistence.

import org.hibernate.annotations.Generated;
import org.hibernate.annotations.GenerationTime;

i hope this can help other people in the future. note this solution is for spring data with postgresql.

  • Related