postgre在 Postgres SQL 中插入期间列 "id" 中的空值



表的结构消息-

id - Integer - NotNull - Primary Key
message - text - NotNull

当我尝试使用插入时

INSERT INTO messages(message) VALUES ('abc');

它给出以下错误-

ERROR:  null value in column "id" of relation "messages" violates not-null constraint
DETAIL:  Failing row contains (null, abc).
SQL state: 23502

提前感谢!

将其添加到实体中

@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;

或者在postgres中将id数据类型更改为串行;

id - serial-Primary Key
message - text - NotNull

类似于:

CREATE TABLE post (
id  SERIAL NOT NULL,
title VARCHAR(255),
PRIMARY KEY (id)
)

串行使用此(strategy = GenerationType.IDENTITY)

根据注释,不能将数据类型更改为serial。在这种情况下,您每次都必须计算新的id。像这样简单的方法

INSERT INTO post (id, message)
(SELECT MAX(id)+1, ' <message here> ' FROM post);

更好的方法是使用序列作为ID。但若你们不能在模式中创建任何东西,那个么你们就不能使用它

https://www.postgresql.org/docs/9.5/sql-createsequence.html

最新更新