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?
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.
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With