错误:关系xxx的列“id”中的空值违反了非空约束 - Spring Data JPA

dev*_*rko 4 java postgresql spring-data spring-data-jpa spring-boot

我有一个关于 Spring JPA 的 @GenerateValue 注释的问题。

这是我的课:

@Entity
@NoArgsConstructor
@Getter
@Setter
public class Product {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    private String name;
    private Double price;
    private Integer quantity;

    @ManyToOne
    private Category category;

    @ManyToOne
    private Manufacturer manufacturer;



    public Product(String name, Double price, Integer quantity, Category category, Manufacturer manufacturer) {
        this.name = name;
        this.price = price;
        this.quantity = quantity;
        this.category = category;
        this.manufacturer = manufacturer;
    }
}
Run Code Online (Sandbox Code Playgroud)

当我尝试添加新产品时,出现此错误:

2021-12-06 18:03:02.013 ERROR 3720 --- [nio-9090-exec-3] o.h.engine.jdbc.spi.SqlExceptionHelper   : ERROR: null value in column "id" of relation "product" violates not-null constraint
  Detail: Failing row contains (null, Dress, 333, 33, 1, 1).
2021-12-06 18:03:02.028 ERROR 3720 --- [nio-9090-exec-3] o.a.c.c.C.[.[.[/].[dispatcherServlet]    : Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Request processing failed; nested exception is org.springframework.dao.DataIntegrityViolationException: could not execute statement; SQL [n/a]; constraint [id" of relation "product]; nested exception is org.hibernate.exception.ConstraintViolationException: could not execute statement] with root cause

org.postgresql.util.PSQLException: ERROR: null value in column "id" of relation "product" violates not-null constraint
  Detail: Failing row contains (null, Dress, 333, 33, 1, 1).
Run Code Online (Sandbox Code Playgroud)

这是我的服务类中的保存方法:

@Override
    public Optional<Product> save(String name, Double price, Integer quantity, Long categoryId, Long manufacturerId) {
        Category category = this.categoryRepository.findById(categoryId).orElseThrow(() -> new CategoryNotFoundException(categoryId));
        Manufacturer manufacturer = this.manufacturerRepository.findById(manufacturerId).orElseThrow(() -> new ManufacturerNotFoundException(manufacturerId));

        this.productRepository.deleteByName(name);

        return Optional.of(this.productRepository.save(new Product(name, price, quantity, category, manufacturer)));
    }
Run Code Online (Sandbox Code Playgroud)

老实说我不明白这是怎么发生的。我读到 PostgreSQL 不支持的地方GenerationType.IDENTITY,但我不认为是这样,因为我对 和Category表使用了相同的生成类型Manufacturer,并且我可以毫无问题地向它们添加新元组。我尝试使用生成类型 SEQUENCE 并且它有效,但我不想使用该生成类型,并且我不明白为什么 IDENTITY在其他 who 表上工作时不能在这里工作。有任何想法吗?

编辑 1:对其进行测试GenerationType.AUTO,它可以工作,但对于 IDENTITY 类型仍然显示相同的错误。

编辑 2:共享用于创建 Product 表和 Category 表的 SQL。

CREATE TABLE IF NOT EXISTS public.product
(
    id bigint NOT NULL,
    name character varying(255) COLLATE pg_catalog."default",
    price double precision,
    quantity integer,
    category_id bigint,
    manufacturer_id bigint,
    CONSTRAINT product_pkey PRIMARY KEY (id),
    CONSTRAINT fk1mtsbur82frn64de7balymq9s FOREIGN KEY (category_id)
        REFERENCES public.category (id) MATCH SIMPLE
        ON UPDATE NO ACTION
        ON DELETE NO ACTION,
    CONSTRAINT fkq5vxx1bolpwm1sngn6krtwsjn FOREIGN KEY (manufacturer_id)
        REFERENCES public.manufacturers (id) MATCH SIMPLE
        ON UPDATE NO ACTION
        ON DELETE NO ACTION
)

TABLESPACE pg_default;

ALTER TABLE public.product
    OWNER to wp;
Run Code Online (Sandbox Code Playgroud)
CREATE TABLE IF NOT EXISTS public.category
(
    id bigint NOT NULL DEFAULT nextval('category_id_seq'::regclass),
    description character varying(4000) COLLATE pg_catalog."default",
    name character varying(255) COLLATE pg_catalog."default",
    CONSTRAINT category_pkey PRIMARY KEY (id)
)

TABLESPACE pg_default;

ALTER TABLE public.category
    OWNER to wp;
Run Code Online (Sandbox Code Playgroud)

最终编辑:我的问题已得到解答,由于某种原因,我的主键未设置为自动增量,这导致了问题。我相信这是因为我仅使用注释创建了表@Id,并且在创建后我添加了生成策略(未将其设置id为自动增量)。

Nah*_*ani 8

为了使其工作,您必须更改产品表中的某些内容。

@GenerateValue(strategy = GenerationType.IDENTITY) 仅适用于您的 ID 列是 SERIAL 类型的情况。

检查 ID 列是否是该类型。例子:

CREATE TABLE Product(
    id SERIAL NOT NULL,
    name VARCHAR(20),
    etc...
)
Run Code Online (Sandbox Code Playgroud)