我有一个关于 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;
}
}
当我尝试添加新产品时,我收到此错误:
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).
这是我的服务类中的保存方法:
@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)));
}
老实说我不明白这是怎么发生的。我在某处读到 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;
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;
最终编辑:我的问题已得到解答,由于某种原因,我的主键未设置为自动增量,这导致了问题。我相信这是因为我仅使用
@Id
注释创建了表,并且在创建后我添加了生成策略(未将 id
设置为自动增量。
要使其正常工作,您必须更改产品表中的某些内容。
@GenerateValue(strategy = GenerationType.IDENTITY) 仅适用于您的 ID 列是 SERIAL 类型的情况。
检查ID列是否是该类型。示例:
CREATE TABLE Product(
id SERIAL NOT NULL,
name VARCHAR(20),
etc...
)
我想总结一下解决问题需要涵盖哪些内容:
Serial
类型的表 CREATE TABLE post (
id SERIAL NOT NULL,
title VARCHAR(255),
PRIMARY KEY (id)
)
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Id
@Column(name = "id", unique = true, nullable = false)
private Integer id;
INSERT INTO post (title)
VALUES ('High-Performance Java Persistence')