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?
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.
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 .
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.