Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use existing Oracle sequence to generate id in hibernate?

I have legacy Oracle db with a sequence named PRODUCT_ID_SEQ.

Here is the mapping of Product class for which I need generate correct ids:

public class Product {    @GeneratedValue(strategy = GenerationType.SEQUENCE,                         generator = "retailerRaw_seq")    @SequenceGenerator(name = "retailerRaw_seq",                        sequenceName = "PRODUCT_ID_SEQ")    private Long id;     ... } 

But looks like ids are generated with an interval of 50, like 1000, 1050, 1100 etc. This corresponds to the default value of allocationSize property = 50. So that means that Hibernate doesn't actually use the sequence which is already defined in the db.

How do I make Hibernate use the sequence?

like image 843
Vladimir Avatar asked Jan 28 '10 14:01

Vladimir


People also ask

Can Hibernate use database sequences to generate primary key?

IDENTITY: Hibernate relies on an auto-incremented database column to generate the primary key, SEQUENCE: Hibernate requests the primary key value from a database sequence, TABLE: Hibernate uses a database table to simulate a sequence.

How does Hibernate sequence generator work?

SEQUENCE Generation. To use a sequence-based id, Hibernate provides the SequenceStyleGenerator class. This generator uses sequences if our database supports them. It switches to table generation if they aren't supported.

How would you implement a custom sequence based id generator?

If you want to use a custom generator, you need to define the generator in a @GenericGenerator annotation and provide the fully-qualified classname as the strategy. You can also configure a set of parameters that will be provided to the configure method when Hibernate instantiates the generator.

Which annotation is used for a custom database sequence in Hibernate?

If you don't provide any additional information, Hibernate will use its default sequence. You can configure the name and schema of the database sequence with a @SequenceGenerator annotation like the one you can see in the following code snippet.


1 Answers

The answer to the original question:

@SequenceGenerator(name="EL_SEQ", sequenceName="EL_SEQ",allocationSize=1) 

It is allocationSize that sets the value to increment by.

like image 170
Mike Demenok Avatar answered Sep 18 '22 22:09

Mike Demenok