問題場景
對pg數據表執行插入語句的時候,報錯如下:
{ "timestamp": 1587012576734, "status": 500, "error": "Internal Server Error", "exception": "org.springframework.jdbc.BadSqlGrammarException", "message": "Request processing failed; nested exception is org.springframework.jdbc.BadSqlGrammarException: \r\n### Error updating database. Cause: org.postgresql.util.PSQLException: ERROR: \"region_info\" is not a sequence\r\n### The error may involve com.hikvision.ctm01taskapp.modules.mapper.RegionDao.insertRegion-Inline\r\n### The error occurred while setting parameters\r\n### SQL: insert into region_info ( create_time, update_time, isvalid, region_code, name, region_path, region_level, sort, geometry ) values ( ?, ?, ?, ?, ?, ?, ?, ?, ? )\r\n### Cause: org.postgresql.util.PSQLException: ERROR: \"region_info\" is not a sequence\n; bad SQL grammar []; nested exception is org.postgresql.util.PSQLException: ERROR: \"region_info\" is not a sequence", "path": "/ctm01taskapp-web/region/insertRegion" }
org.postgresql.util.PSQLException: ERROR: \"region_info\" is not a sequence
由於以前沒用過pg數據庫,從來沒遇到過這個問題,百度得知sequence是pg數據庫中用於主鍵自增長的,於是考慮應該是insert插入時自增長的id主鍵插入報錯,拉出建表源代碼:
CREATE TABLE public.region_info ( id int4 NOT NULL, -- 數據庫自增id create_time timestamp NULL DEFAULT now(), -- 入庫時間 update_time timestamp NULL DEFAULT now(), -- 更新時間 isvalid int2 NULL, -- 0.否;1.是,默認為1 region_code varchar(64) NULL, -- 行政區划編碼 parent_region_code varchar(64) NULL, -- 父編碼 "name" varchar(64) NULL, -- 行政區划名稱 region_path varchar(255) NULL, -- 行政區划路徑 region_level int2 NULL, -- 層級 sort int2 NULL, -- 排序 geometry text NULL, CONSTRAINT region_info_pkey PRIMARY KEY (id) ); COMMENT ON TABLE public.region_info IS '行政區划信息表';
id int4 NOT NULL, -- 數據庫自增
果然有問題,id並沒有實現遞增。於是修改sql代碼如下:
--創建一個sequence seq_region_info create sequence seq_region_info increment by 1 minvalue 1 no maxvalue start with 11;
--將需要自增的主鍵id與seq_region_info關聯 ALTER TABLE public.region_info ALTER COLUMN id SET DEFAULT nextval('seq_region_info'::regclass);
至此,id便可以實現自增了