2

I would like to make a unique field "number" with autogeneration(autoincrement, last number + 1). But it is not an id field. How can i reach that? @GeneratedValue doesn't work. Only id was generated. My code doens't work.

My entity

@Entity
@Table(schema = "public")
public class Policeman implements Serializable {

    @Id
    @GeneratedValue
    private Long id;

    @Column
    @GeneratedValue(strategy = GenerationType.SEQUENCE)
    private Long number;

    @Column
    private String fam;

    @Column
    private String name;

    @Column
    private String otch;

   //setters getters
}
Vytsalo
  • 670
  • 3
  • 9
  • 19

1 Answers1

2

This SO question looked the same: Link1

It says that the @GeneratedValue annotation is only used in conjunction with @Id to create auto-numbers. It cannot be used with non-id columns. However, there is a workaround that suggests to create a separate entity with a generated Id, something like this:

@Entity
public class GeneralSequenceNumber {
  @Id
  @GeneratedValue(strategy = GenerationType.SEQUENCE)
  private Long number;
}

@Entity
@Table(schema = "public")
public class Policeman implements Serializable {

    @Id
    @GeneratedValue
    private Long id;

    @OneToOne(...)
    private GeneralSequnceNumber myVal;

    @Column
    private String fam;

    @Column
    private String name;

    @Column
    private String otch;

   //setters getters
}

You can also refer to the following link for more details on this work-around:Link2

I hope it helps.

aru_sha4
  • 368
  • 2
  • 11
  • Thanks for answer, but i think it is too redundantly use additional class to solve this simple problem – Vytsalo Jan 14 '20 at 10:03