无法更新NaturalId字段值:实体{Model}的不可变自然标识符从ABC更改为XYZ

时间:2019-07-04 07:36:57

标签: java spring-boot

在JPA中使用spring-boot: 试图做更新表。但是在更新NaturalId字段值时出现错误。

ERROR:nested exception is org.hibernate.HibernateException: An immutable natural identifier of entity com.model.Company was altered from SOL to MEP

模型实体:

  @Id
  @GeneratedValue(strategy = GenerationType.IDENTITY)
  @Column(name = "COMPANY_ID")
  private Long companyId;

  @NotBlank
  @NaturalId
  @Size(max = 5)
  @Column(name = "COMPANY_CODE")
  private String companyCode;    

控制器和服务:

@PutMapping("/company")
public ResponseEntity<?> updateCompany(@Valid @RequestBody CompanyRequest companyRequest) {
    logger.info("UPDATE COMPANY :  {} ", companyRequest);

    Company company = companyService.updateCompany1(companyRequest);

    URI location = ServletUriComponentsBuilder
                .fromCurrentRequest().path("/{companyId}")
                .buildAndExpand(company.getCompanyId()).toUri();

    return ResponseEntity.created(location)
                .body(new ApiResponse(true, "Company Updated Successfully"));
}

//Services:
public Company updateCompany1(CompanyRequest companyRequest) {
        Company company = companyRepository.findById(companyRequest.getCompanyId())
                    .orElseThrow(() -> new ResourceNotFoundException("Company", "companyId", companyRequest.getCompanyId()));
        company.setCompanyCode(companyRequest.getCompanyCode());
        return companyRepository.saveAndFlush(company);
}

1 个答案:

答案 0 :(得分:1)

1)在NaturalId上设置mutable属性,并2)使您的列唯一:

您的映射应如下所示:

@NotBlank
@NaturalId(mutable=true)
@Size(max = 5)
@Column(name = "COMPANY_CODE", unique=true)
private String companyCode;