here is my service method
public Employee updateByEmployeeIdAndFirstName(Long employeeId, String firstName, Employee employeesDetails){
Employee updateEmployee = employeeRepository.findByEmployeeIdAndFirstName(employeeId, firstName).get(0);
if (employeesDetails.getFirstName() != null ) {
updateEmployee.setFirstName(employeesDetails.getFirstName());
}
if (employeesDetails.getLastName() != null ) {
updateEmployee.setLastName(employeesDetails.getLastName());
}
if (employeesDetails.getEmail() != null ) {
updateEmployee.setEmail(employeesDetails.getEmail());
}
if (employeesDetails.getPhoneNumber() != null ) {
updateEmployee.setPhoneNumber(employeesDetails.getPhoneNumber());
}
if (employeesDetails.getHireDate() != null ) {
updateEmployee.setHireDate(employeesDetails.getHireDate());
}
if (employeesDetails.getJob() != null ) {
updateEmployee.setJob(employeesDetails.getJob());
}
if (employeesDetails.getSalary() != null ) {
updateEmployee.setSalary(employeesDetails.getSalary());
}
if (employeesDetails.getCommissionPct() != null ) {
updateEmployee.setCommissionPct(employeesDetails.getCommissionPct());
}
if (employeesDetails.getManager() != null ) {
updateEmployee.setManager(employeesDetails.getManager());
}
if (employeesDetails.getDepartment() != null ) {
updateEmployee.setDepartment(employeesDetails.getDepartment());
}
employeeRepository.save(updateEmployee);
return updateEmployee;
}
here is my mapping method
@PutMapping(path = "/update")
public ResponseEntity updateEmployee(@RequestParam("id") Long employeeId, @RequestParam("firstName") String firstName, @RequestBody Employee employeesDetails) {
return ResponseEntity.ok(employeeService.updateByEmployeeIdAndFirstName(employeeId, firstName, employeesDetails));
}
i want to make my update method more flexible with looping so no need to use a lot of if
CodePudding user response:
It's not the looping solution, but you can also remove ifs with Optional, for example:
Optional.ofNullable(employeesDetails.getEmail()).ifPresent(updateEmployee::setEmail);
CodePudding user response:
If any fields need to be assigned, i think you can use reflection
Field[] fields = employeesDetails.getClass().getDeclaredFields();
for (int i = 0; i < fields.length; i ) {
fields[i].setAccessible(true);
Object value = fields[i].get(employeesDetails);
fields[i].set(updateEmployee, value);
System.out.println(fields[i].get(updateEmployee));
}