How to define custom sequence generator used for Id (primary) in JPA?

342 Views Asked by At

My application is using JPA for persisting data to Database. The application has to generate Custom(encoded) sequence for performance reasons. By default JPA seems to generate Ids for an entity using some sequence.

How to override default sequence generator with customer sequence generator in Java ? I want to have sequence generator in Java as I have a separate logic for that.

1

There are 1 best solutions below

0
aleksey.stukalov On

This is how you go with the custom sequence:

@Id
@SequenceGenerator(name = "pet_seq", 
        sequenceName = "pet_sequence", 
        initialValue = 1, allocationSize = 20)
@GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "pet_seq")
@Column(name = "id", nullable = false)
private Long id;

In this case it will use pet_sequence instead of the default one. Also you can read this article for a better understanding of this subject.