我有2个实体:
public class Brand {
@OneToMany(mappedBy = "brand", cascade = CascadeType.ALL, fetch = FetchType.LAZY)
@JsonView(Views.Detailed.class)
@JsonManagedReference("brand-departments")
private List<Department> departments;
}
public class Department {
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "brand_id", nullable = false)
@JsonBackReference("brand-departments")
private Brand brand;
}
更新Department
时,我在我的控制器中执行以下操作:
public ResponseEntity<MappingJacksonValue> update(@PathVariable Long brandId,
@Valid @RequestBody Department department, BindingResult bindingResult) throws Exception {
if (bindingResult.hasErrors()) {
throw new InvalidRequestException("Invalid Department", bindingResult);
}
Department existingDepartment = departmentService.findById(department.getId());
BeanUtils.copyProperties(department, existingDepartment, "brand");
this.departmentService.update(existingDepartment);
MappingJacksonValue mappingJacksonValue = jsonView(JSON_VIEWS.SUMMARY.value, department);
return new ResponseEntity<>(mappingJacksonValue, HttpStatus.OK);
}
我在复制属性时忽略brand
的原因是因为@RequestBody Department department
的品牌为NULL。当我查找existingDepartment
时,它拥有正确的品牌。但是,当我更新部门时,它会失败,因为它说BRAND_ID
为NULL。但我已经证实它不是NULL。
如果我执行以下操作:
public ResponseEntity<MappingJacksonValue> update(@PathVariable Long brandId,
@Valid @RequestBody Department department, BindingResult bindingResult) throws Exception {
if (bindingResult.hasErrors()) {
throw new InvalidRequestException("Invalid Department", bindingResult);
}
Department existingDepartment = departmentService.findById(department.getId());
existingBrand.setBrand(new Brand(brandId));
BeanUtils.copyProperties(department, existingDepartment);
this.departmentService.update(existingDepartment);
MappingJacksonValue mappingJacksonValue = jsonView(JSON_VIEWS.SUMMARY.value, department);
return new ResponseEntity<>(mappingJacksonValue, HttpStatus.OK);
}
(将brand
上的existingDepartment
设置为仅具有ID的非会话连接对象)更新正常运行。所以有一些事实是existingDepartment
引用了一个完整的数据库获取版本brand
导致更新失败,但我不确定原因。