[英]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();
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.