用@GenericGenerator替换@SequenceGenerator

时间:2018-01-03 13:39:12

标签: java spring postgresql hibernate

(Hibernate 5,PostgreSQL 9.6,Java 8,Spring ORM 4.3.6)

以下实体类Car运行良好:

import javax.persistence.*;

@Entity
@SequenceGenerator(name = "carSequence", sequenceName = "car_id_seq", )
@Table(name = "car")
public class Car {

    @Id
    @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "carSequence")
    private Long id;
    //...
}

它基于以下SQL(简化):

CREATE TABLE car (id bigint NOT NULL);
ALTER TABLE car ADD CONSTRAINT PK_car PRIMARY KEY (id);

但是,我得到了这个警告,我想解决这个问题:

WARN org.hibernate.orm.deprecation: HHH90000014: Found use of deprecated [org.hibernate.id.SequenceHiLoGenerator] sequence-based id generator; use org.hibernate.id.enhanced.SequenceStyleGenerator instead.  See Hibernate Domain Model Mapping Guide for details.

所以,我用旧车取代了旧车:

import org.hibernate.annotations.GenericGenerator;
import javax.persistence.*;

@GenericGenerator(
    name = "carSequence",
    strategy = "org.hibernate.id.enhanced.SequenceStyleGenerator",
    parameters = {
            @org.hibernate.annotations.Parameter(name = "sequence_name", value = "car_id_seq"),
            @org.hibernate.annotations.Parameter(name = "initial_value", value = "1"),
            @org.hibernate.annotations.Parameter(name = "increment_size", value = "50")
    }
)
@Table(name = "car")
public class Car {

    @Id
    @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "carSequence")
    private Long id;
    //...
}

然而,我的代码中出现了错误:

Caused by: org.postgresql.util.PSQLException: ERROR: duplicate key value violates unique constraint "pk_car"
   Detail: Key (id)=(-34) already exists.

奇怪的是:-34似乎很奇怪 其他奇怪的事情:序列生成重复键。

汽车表已经填满,直到id = 709。 在序列定义上,curval = 15, nextval = 16 and increment = 1

1 个答案:

答案 0 :(得分:1)

您未指定要使用的优化程序。

在您的第一个变体中,您使用的是SequenceHiLoGenerator,在第二个变体中,您只需指定增量大小而不将优化器设置为HiLo。

根据文档(SequenceStyleGenerator),如果没有指定,Hibernate会选择一个生成器。因为increment_size是> 1(see here)Hibernate可能会选择与seqHiLo不同的pooled-lo优化器。

所以,你应该添加

@Parameter(name = "optimizer", value = "hilo"),

到您的参数,以便将优化器设置为seqhilo