So I encountered this issue with updating an entity in DB. while Passing a whole entity and updating only specific fields it treats untouched fields as null, as a result I get an exception since those fields are @Not-Null,
I have tried looking for similar problems but could not fix my problem.
Company ENTITY:
@Entity @Table (name = "companies") @Data @ToString(exclude = "perfumes") @AllArgsConstructor @NoArgsConstructor @Builder public class Company { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private int id; @NotNull private String name; @NotNull @Email(message = "Wrong input. please enter a VALID email address") private String email; @NotNull @Size(min = 4, max = 14, message = "Password range must be between 4 - 14 digits") private String password; @NotNull @Enumerated(EnumType.STRING) private Country country; @Singular @OneToMany(mappedBy = "company", fetch = FetchType.LAZY, cascade = CascadeType.ALL) private List<Perfume> perfumes = new ArrayList<>(); } Most fields are @NotNull for creation, however, I need to update the entity, sometimes only specific fields.
Service:
@Override public String updateCompany(int id, Company company) throws DoesNotExistException { if(!companyRepository.existsById(id)) { throw new DoesNotExistException(id); } companyRepository.saveAndFlush(company); return company.getName() + " has been UPDATED"; } as you can see an ENTITY has been passed which causes rest of attributes to be automatically null if not modified.
Controller:
@PutMapping("/updateCompany/{id}") @ResponseStatus(HttpStatus.ACCEPTED) public String updateCompany(@PathVariable int id, @RequestBody Company company) throws DoesNotExistException { return admin.updateCompany(id,company); } EXCEPTION:
Validation failed for classes [com.golden.scent.beans.Company] during update time for groups [javax.validation.groups.Default, ] List of constraint violations:[ ConstraintViolationImpl{interpolatedMessage='must not be null', propertyPath=password, rootBeanClass=class com.golden.scent.beans.Company, messageTemplate='{javax.validation.constraints.NotNull.message}'} ] Thanks.