java 中没有 @Id 注释的序列生成器,在一个范围内的 Postgres 中休眠

Sequence Generator without @Id annotation in java with hibernate in Postgres within a range

我有一个 REST API,其中有人,现在我有一个数字范围 (40000 - 99999),我必须在最后填充并将其保存到数据库,我不会把它放在请求的正文中。但是我仍然必须按顺序坚持这个数字

例如:Postgres 中的 40001、40002、40003 等,因为它不是 @Id 字段,所以我无法找到将它保存在数据库中的方法,有什么方法可以用 Java, JPA?

CREATE SEQUENCE public.certificate
    INCREMENT 1
    START 40000
    MINVALUE 40000
    MAXVALUE 99999999
    CACHE 1;

create table CertificateNumber (c_number integer default nextval(‘certificate’));

@Generated(value = GenerationTime.INSERT)
@Column(name = "c_number", insertable = false,updatable = false)
Integer certificateNumber;

 Resolved [org.springframework.dao.DataIntegrityViolationException: could not execute statement; SQL [n/a]; constraint [certificate_number]; nested exception is org.hibernate.exception.ConstraintViolationException: could not execute statement]
2020-03-06 16:33:13.167  INFO 864 --- [nio-8080-exec-2] i.StatisticalLoggingSessionEventListener : Session Metrics {
    714213 nanoseconds spent acquiring 1 JDBC connections;
    0 nanoseconds spent releasing 0 JDBC connections;
    3037131 nanoseconds spent preparing 1 JDBC statements;
    18543560 nanoseconds spent executing 1 JDBC statements;
    0 nanoseconds spent executing 0 JDBC batches;
    0 nanoseconds spent performing 0 L2C puts;
    0 nanoseconds spent performing 0 L2C hits;
    0 nanoseconds spent performing 0 L2C misses;
    67929213 nanoseconds spent executing 1 flushes (flushing a total of 1 entities and 0 collections);
    0 nanoseconds spent executing 0 partial-flushes (flushing a total of 0 entities and 0 collections)
}

作为对 API 的回应,下面也提到了我得到的内容。

{
    "apierror": {
        "status": "INTERNAL_SERVER_ERROR",
        "timestamp": "06-03-2020 04:33:13",
        "message": "Unexpected error",
        "debugMessage": "could not execute statement; SQL [n/a]; constraint [certificate_number]; nested exception is org.hibernate.exception.ConstraintViolationException: could not execute statement",
        "subErrors": null
    }
}

我建议在你的数据库中使用触发器,首先你创建你的序列:

CREATE SEQUENCE certificateNumber_table_seq
INCREMENT 1
START 1; 

然后创建这个函数:

CREATE OR REPLACE FUNCTION trigger_function()
RETURNS trigger AS
$BODY$
BEGIN
New.c_number:=nextval('certificateNumber_table_seq');
Return NEW;
END;
$BODY$

最后是您的触发器,它将执行您创建的函数

DROP TRIGGER IF EXISTS trigg_auto_increment ON table_name;
CREATE TRIGGER trigg_auto_increment
BEFORE INSERT
ON table_name //the name of your table
FOR EACH ROW
EXECUTE PROCEDURE trigger_function();