Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

unable to update NaturalId field value: An immutable natural identifier of entity {Model} was altered from ABC to XYZ

Using spring-boot with JPA: trying to do Update table. but getting error when i update NaturalId field value.

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

Model Entity:

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

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

Controller & Service :

@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);
}
like image 831
uday Avatar asked Nov 28 '25 19:11

uday


1 Answers

1) set the mutable attribute on the NaturalId and 2) make your Column unique:

Your mapping should look like:

@NotBlank
@NaturalId(mutable=true)
@Size(max = 5)
@Column(name = "COMPANY_CODE", unique=true)
private String companyCode; 
like image 154
Simon Martinelli Avatar answered Dec 01 '25 07:12

Simon Martinelli



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!