Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Multiple SequenceGenerator in Hibernate Entity

Is it possible to use 2 sequence generators in Hibernate Entity Class. I want to use two sequence generator for my case one for the primary key and other for a simple field. How can i achieve the same?

@Data
@Table(name="a_b")
@SequenceGenerator(name = "a1_seq", sequenceName = "a1_seq", allocationSize    = 1)
@SequenceGenerator(name = "b1_seq", sequenceName = "b1_seq", allocationSize = 1)
public class ABC {

    @Id
    @Column(name = "id")
    @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "a1_seq")
    private Integer id;

    @Column(name = "c")
    private String c;

    @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "b1")
    @Column(name = "b)
    private Integer b;

}
like image 648
Siddharth Agarwal Avatar asked Nov 29 '25 13:11

Siddharth Agarwal


1 Answers

You should have only one SequenceGenerator for the Primary Key:

@Id
@Column(name = "id")
@SequenceGenerator(name = "a1_seq", sequenceName = "a1_seq", allocationSize    = 1)
@GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "a1_seq")
private Integer id;

and for the foreign key you could have:

@Column(name = "b, columnDefinition="serial")
private Integer b;

which should work for PostgreSQL.

like image 143
Vlad Mihalcea Avatar answered Dec 01 '25 07:12

Vlad Mihalcea



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!