我有两个实体类,具有双向的一对多关系的商品和类别。
下面是实体类,Category
实体;
@Entity
@Data
@AllArgsConstructor
@Builder
public class Category implements Serializable {
@Id
@GeneratedValue(strategy = GenerationType.TABLE)
private Long idCategory;
private String categoryName;
@OneToMany(mappedBy = "category", cascade = CascadeType.ALL)
private List<Article> articles;
}
Article
实体;
@Entity
public class Article implements Serializable {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long idArticle;
private String designation;
private BigDecimal prixUnitaire;
private BigDecimal tauxTva;
private BigDecimal prixUnitaireTTC;
@Lob
private byte[] photo;
private boolean checked;
@Transient
private Long idOwner;
@ManyToOne
@JoinColumn(name = "idCategory")
private Category category;
}
我的休息控制器;
@PostMapping("/")
public ResponseEntity createArticle(@RequestBody Article article){
if(article == null){
return ResponseEntity.badRequest().body("cannot create article with empty fields");
}
return ResponseEntity.ok(articleRepository.save(article));
}
我通过邮递员发送的JSON数据:
{
"designation" : "poupee",
"prixUnitaire" : "10000",
"tauxTva" :"1",
"prixUnitaireTTC" : "900",
"category" : "1"
}
创建新对象时,我收到的ForeignKey为null。我有idCategory NULL
有两个问题;
您正在category
对象内发送article
的怪异值。尝试发送类似的内容;
{
...
"category" : {
"categoryName": "1"
}
}
如果您打算通过categoryName
传递"category": "1"
从article
的角度来看,缺少级联配置,因此,文章无法强制执行category
的创建。要启用此功能,您需要更新与此关系;
@ManyToOne(cascade = CascadeType.PERSIST)
@JoinColumn(name = "idCategory")
private Category category;