简体   繁体   English

由于 schema.sql 和休眠导致的唯一约束错误

[英]Unique constraint error due to schema.sql and hibernate

I'm making a spring boot application where I'm first creating a table in DB and loading some initial data into it using schema.sql and data.sql method .我正在制作一个 Spring Boot 应用程序,我首先在 DB 中创建一个表,并使用schema.sql 和 data.sql 方法将一些初始数据加载到其中。

Below is schema.sql:下面是schema.sql:

DROP TABLE IF EXISTS EMPLOYEE;

CREATE TABLE EMPLOYEE(
  ID INT NOT NULL AUTO_INCREMENT,
  NAME VARCHAR(100) NOT NULL,
  SALARY DECIMAL NOT NULL,
  LAST_UPDATE TIMESTAMP NOT NULL,
  PRIMARY KEY ( ID )
);

Below is the entity:下面是实体:

@Entity
@Getter
@Setter
@NoArgsConstructor
public class Employee {

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

    @Column(name = "name")
    private String name;

    @Column(name = "salary")
    private Double salary;

    @Column(name = "last_update")
    private Timestamp lastUpdate;

    public Employee(String name, Double salary) {
        this.name = name;
        this.salary = salary;
        this.lastUpdate = new Timestamp(System.currentTimeMillis());
    }

}

When I'm performing a POST operation with below json payload, I'm getting error: Unique index or primary key violation: "PRIMARY KEY ON PUBLIC.EMPLOYEE(ID) [1, 'RAGHU', 250.1, TIMESTAMP '2022-04-23 00:00:00']";当我使用以下 json 有效负载执行POST操作时,出现错误: Unique index or primary key violation: "PRIMARY KEY ON PUBLIC.EMPLOYEE(ID) [1, 'RAGHU', 250.1, TIMESTAMP '2022-04-23 00:00:00']";

Json payload of POST request: POST 请求的 Json 有效载荷:

{
    
    "name": "Adam",
    "salary": 257.1,
    "last_update": "2022-04-22T18:30:00.000+00:00"
}

Application properties:应用属性:

spring.datasource.url=jdbc:h2:mem:testdb
spring.datasource.driverClassName=org.h2.Driver
spring.datasource.username=sa
spring.datasource.password=abc123
spring.jpa.database-platform=org.hibernate.dialect.H2Dialect
spring.h2.console.enabled=true
logging.level.org.hibernate.SQL=debug
logging.level.org.hibernate.type.descriptor.sql=trace
spring.jpa.hibernate.ddl-auto=update
spring.jpa.defer-datasource-initialization=true

It seems to me hibernate is conflicting with my initial data load.在我看来,休眠与我的初始数据加载冲突。 How can I fix it?我该如何解决?

You need to change the GenerationType to IDENTITY .您需要将 GenerationType 更改为IDENTITY I think Hibernate at the moment is using a sequence starting from 1.我认为 Hibernate 目前正在使用从 1 开始的序列。

The mapping will look like:映射将如下所示:

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

You can enable SQL logging to verify that's actually running the correct queries:您可以启用 SQL 日志记录以验证实际运行的是正确的查询:

hibernate.show_sql = true
hibernate.format_sql = true

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM