【发布时间】:2021-01-26 14:55:53
【问题描述】:
我使用 Spring Boot / Hibernate / JPA 创建新产品并获得列 'brand_id' cannot be null 错误。我不知道为什么会发生这个错误。谁能解释我哪里错了?
产品:
@Entity
public class Product {
@javax.persistence.Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long Id;
@NotBlank(message = "Product name is required")
private String name;
private String image;
private String description;
private double price;
private int countInStock;
private double rating;
private int numReviews;
@ManyToOne(fetch = FetchType.EAGER)
@JoinColumn(name = "brand_id", updatable = false, nullable = false)
@JsonIgnore
private Brand brand;
@ManyToMany
@JoinTable(name = "product_category", joinColumns = @JoinColumn(name = "product_id"), inverseJoinColumns = @JoinColumn(name = "category_id"))
@JsonIgnore
private List<Category> categories;
品牌:
@Entity
public class Brand {
@javax.persistence.Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long Id;
@NotBlank(message = "Brand name is required")
private String name;
@OneToMany(cascade = CascadeType.REFRESH, fetch = FetchType.LAZY, mappedBy = "brand", orphanRemoval = true)
private List<Product> products;
类别:
@Entity
public class Category {
@javax.persistence.Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long Id;
@NotBlank(message = "Category name is required")
private String name;
@ManyToMany(mappedBy = "categories")
private List<Product> products;
还有我用来输入的产品对象创建新产品:
{
"name": "test",
"image": "/images/test.jpg",
"description": "test",
"brand_id": 4,
"category_id": 1,
"price": 99.99,
"countInStock": 100,
"rating": 4.5,
"numReviews": 120
}
【问题讨论】:
-
我想我可以帮助你,但我需要更多信息。我相信您在创建产品而不提供品牌变量时会遇到此异常?
-
好吧。我已经通过了“brand_id”:4,所以我认为这对于“品牌变量”就足够了吗?
-
我的品牌 ID 为 4:{ "id" : 1, "name" : "Apple" }, { "id" : 2, "name" : "Cannon" }, { " id”:3,“名称”:“索尼”},{“id”:4,“名称”:“罗技”},{“id”:5,“名称”:“亚马逊”}
-
您确实传递了数据
brand_id:4,但是您的代码是否在任何时候都将整数4转换为带有Id=4的 Brand 对象?这就是我所说的更多信息。您没有显示失败操作的实际代码。 -
你能告诉我将整数
4转换为带有Id=4的 Brand 对象的代码吗?
标签: java mysql spring spring-mvc spring-data-jpa