0

表格消息的结构-

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

提前致谢 !

4

2 回答 2

1

将此添加到您的实体中

    @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)

于 2021-03-30T14:08:50.783 回答
0

根据评论将数据类型更改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

于 2021-03-30T14:14:49.290 回答