The Hibernate hilo strategy does not generate the values according to the next database sequence value

1k Views Asked by At

I have a jpa configuration like this:

    @Id
    //@GeneratedValue(strategy=GenerationType.SEQUENCE, generator="seq_gen")
    @GeneratedValue(generator = "timedep_seq_gen")
    @GenericGenerator(
             name = "seq_gen",
             strategy = "org.hibernate.id.enhanced.SequenceStyleGenerator",
                     parameters = {
                                @Parameter(name = "sequence_name", value = "sequence_myseq"),
                                @Parameter(name = "initial_value", value = "1"),
                                @Parameter(name = "increment_size", value = "10"),
                                @Parameter(name = "optimizer", value ="hilo")
                                }
            )
    private Long id;

The insertions are creating id values like 1,2,3.. and this is fine till I manually do

SELECT nextval('sequence_myseq');

I expect that on running the above from pgadmin(or any other client), the next set of values generated by the jpa/hibernate generator should skip the values for the id column, but that is not the case. It still generates the values without skipping any id values. What is the problem here ?

EDIT 1 Till I get some concrete answer, looks like hilo optimization will not work for multiple instances. The following is working but it needs you to set

 increment by 10 

in your sequence definition as well.

@GeneratedValue(generator = "dep_seq_gen")
    @SequenceGenerator(
            name = "dep_seq_gen",
            sequenceName = "sequence_dep",
            allocationSize = 10
        )
1

There are 1 best solutions below

5
Vlad Mihalcea On

Hilo limitations

Hilo algorithm is not interoperable with systems that don't know the hilo allocations scheme, and this is why Hibernate supports the pooled optimizer.

Pooled optimizer

Unlike hilo, the pooled optimizer includes the database sequence values in the identifier values allocated by the application. For this reason, any new sequence value is not going to conflict with previous or future values.

Since pooled is used by default, you can also simplify your @Id mapping using the SequenceGenerator instead of the more verbose @GenericGenerator you used for hilo:

@Id
@GeneratedValue(
    strategy = GenerationType.SEQUENCE,
    generator = "sequence_myseq"
)
@SequenceGenerator(
    name = "sequence_myseq",
    sequenceName = "sequence_myseq",
    allocationSize = 3
)
private Long id;

Migrating from hilo to pooled

If you used hilo and want to migrate to the pooled optimizer, you will need to change the sequence value as, otherwise, conflicts will be generated.