pg数据库org.postgresql.util.PSQLException: ERROR: "xxx" is not a sequence

问题场景

对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: 
### Error updating database.  Cause: org.postgresql.util.PSQLException: ERROR: "region_info" is not a sequence
### The error may involve com.hikvision.ctm01taskapp.modules.mapper.RegionDao.insertRegion-Inline
### The error occurred while setting parameters
### SQL: insert into region_info        ( create_time,                                     update_time,                                     isvalid,                                     region_code,                                                name,                                     region_path,                                     region_level,                                     sort,                                     geometry )           values ( ?,                                           ?,                                           ?,                                           ?,                                                        ?,                                           ?,                                           ?,                                           ?,                                           ? )
### Cause: org.postgresql.util.PSQLException: ERROR: "region_info" is not a sequence
; 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便可以实现自增了


原文地址:https://www.cnblogs.com/jxxblogs/p/12712522.html