使用完整参考更新ManyToOne对象

时间:2016-10-21 20:59:30

标签: spring hibernate jpa spring-boot

我有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导致更新失败,但我不确定原因。

0 个答案:

没有答案