使用 Postman 请求时,H2 数据库中的 AUTO_INCREMENT 不起作用

问题描述

我想在 H2 DB 中持久化 Todo,以促进 Spring Boot 应用程序。

以下 sql 脚本初始化数据库并且它正常工作:

DROP TABLE IF EXISTS todos;

CREATE TABLE todos (
  id INT AUTO_INCREMENT PRIMARY KEY,title VARCHAR(50) NOT NULL UNIQUE,description VARCHAR(250) NOT NULL,completion_date DATE,priority VARCHAR(6) CHECK(priority IN ('LOW','MEDIUM','HIGH'))
);

INSERT INTO todos (title,description,priority) VALUES
  ('Create xxx Todo','An xxx-Todo must be created.','HIGH'),('Delete xxx Todo','An xxx-Todo must be deleted.',('Update xxx Todo','An xxx-Todo must be updated.','MEDIUM'),('Complete xxx Todo','An xxx-Todo must be completed.','LOW');

启动 Spring Boot 时的控制台输出

Hibernate: drop table if exists todos CASCADE 
Hibernate: drop sequence if exists hibernate_sequence
Hibernate: create sequence hibernate_sequence start with 1 increment by 1
Hibernate: create table todos (id bigint not null,completion_date date,description varchar(250) not null,priority varchar(250) not null,title varchar(50) not null,primary key (id))
Hibernate: alter table todos add constraint UK_c14g1nqfdaaixe1nyw25h3t0n unique (title)

我在 Spring Boot 应用程序中用 Java 实现了控制器、服务和存储库。 我使用 Postman 来测试实现的功能并让所有 Todos 运行良好,但由于一个

,创建 Todo 前 4 次失败
org.h2.jdbc.JdbcsqlIntegrityConstraintViolationException: Unique index or primarky key violated: "PRIMARY KEY ON PUBLIC.TodoS(ID) [1,'Create xxx Todo','An xxx Todo must be created.',NULL,'HIGH']"

这是请求正文:

{
    "title": "Creating xxxx Todo via API","description": "An xxxx Todo was created via API.","id": null,"completionDate": null,"priority": "LOW"
}

此异常发生 4 次,响应如下:

{
    "timestamp": "2021-05-25T17:32:57.129+00:00","status": 500,"error": "Internal Server Error","message": "","path": "/api/todo/create"
}

第五次尝试创建 Todo

{
    "title": "Create xxxx Todo via API","id": 5,"priority": "LOW"
}

并且 ID 5 已分配给此记录。 因此,问题似乎是Spring Boot启动并初始化H2数据库时H2启动期间插入的记录数。

在 Todo 实体中,我将 id 注释如下:

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

如何解决这个问题,当我尝试通过 postman 访问 Spring Boot 应用程序的创建端点时?

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)