2
votes

I have defined a sequence in my liquibase changelog, but looks like Hibernate is ignoring it when inserting the entities.

Sequence defined in Liquibase looks like this.

<createSequence cycle="false" incrementBy="1"
            startValue="1" maxValue="9223372036854775807" minValue="1"
            sequenceName="seq_vehicle" />

And in the Entity class.

@Entity
@Table(name = "VEHICLE")
public class Vehicle {

    @Id
    @Column(name = "ID")
    @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "VEHICLE_SEQ")
    @SequenceGenerator(name = "VEHICLE_SEQ", sequenceName = "SEQ_VEHICLE")
    private Long id;

I also added this property to hibernate.cfg.xml

<property name="hibernate.id.new_generator_mappings">false</property>

The problem is that whenever new entity is inserted to the DB, it just ignores Liquibase sequence, and starts from 50 and increments by 50 for any new insert. How do I fix that?

2
Try to put in lowercase the sequence name: sequenceName = "seq_vehicle" on @SequenceGeneratorDherik

2 Answers

0
votes

Use @GenericGenerator instead of @SequenceGenerator.

@Id
@Column
@GenericGenerator(
    name = "VEHICLE_SEQ", 
    strategy = "sequence", 
    parameters = {
        @org.hibernate.annotations.Parameter(name = "sequence", value = "SEQ_VEHICLE")
    }
)
@GeneratedValue(generator = "VEHICLE_SEQ")
private Long id;

The @SequenceGenerator in your case hibernate's HILO mechanism which, by default, uses default allocation size of 50, and that's why you see gaps in id values id the database.

0
votes

Just add allocationSize = 1:

@Id
@Column(name = "ID")
@GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "VEHICLE_SEQ")
@SequenceGenerator(name = "VEHICLE_SEQ", sequenceName = "SEQ_VEHICLE", allocationSize = 1)
private Long id;

As @veljkost explained, the default value for the allocationSize is 50.