我正在使用 spring 和 hibernate 开发一个 Restful 应用程序。
我正在发布此 JSON
{
"name": "Test Category",
"parent": 2
}
由此,我无法在 Controller post 方法中获取父 ID。当我使用 theCategory.getParent() 时,它返回 null。
这是我的 Controller 发布方法。
@PostMapping("/categories")
public Category addCategory(@RequestBody Category theCategory) {
System.out.println("The parent category : " + theCategory.getParent());
// set id to 0
theCategory.setId(0);
categoryService.saveCategory(theCategory);
return theCategory;
}
当我保存类别时,设置父类别的最佳方法是什么?这是我的类别 - https://github.com/iyngaran/test/blob/master/Category.java
最佳答案
您的 getParent()
上有 @JsonIgnore
。这就是为什么你的对象得到 null 的原因。
(当您删除@JsonIgnore
时,您将收到绑定(bind)错误)。
因此,我建议您发布 DTO 对象,而不是实体。
在此 dto 对象中,您可以将父级映射到整数,而在 Category
类中,您可以将其映射到 Parent
。
关于java - 保存类别时如何设置父类别?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56129281/