In the below code, I have two objects of same class. One object (A - employeeObjectInDatabase) has all the fields set. Another object (B - employeeObjectForUpdate) has only few of the fields set. basically I need to set not null values of Object B to Object A. Below code has 'if not null' check for each field to set the value. Is there any other better way to get this done?
Is there a better way to replace the code between comments "BLOCK 1 BEGIN" and "BLOCK 1 END"?
In case of classes with few fields, checking for if not null is easy, but in case of 20+ fields there is a lot of if not null check required, hence thought of getting expert opinion.
Sample:
public class Employee {
private String id;
private String name;
private String department;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getDepartment() {
return department;
}
public void setDepartment(String department) {
this.department = department;
}
public static void main(String[] args) {
Employee newEmployeeObject = new Employee();
newEmployeeObject.setId("A100");
newEmployeeObject.setName("Albert");
newEmployeeObject.setName("Physics");
//newEmployeeObject is persisted into database
Employee employeeObjectForUpdate = new Employee();
employeeObjectForUpdate.setId("A100");
employeeObjectForUpdate.setName("Albert Einstein");
//Inorder to update only the fields that are not null
Employee employeeObjectInDatabase = employeeDao.getEmployee();
//BLOCK 1 BEGIN
if (null != employeeObjectForUpdate.getName())
employeeObjectInDatabase.setName(employeeObjectForUpdate.getName());
if (null != employeeObjectForUpdate.getDepartment())
employeeObjectInDatabase.setDepartment(employeeObjectForUpdate.getDepartment());
//BLOCK 1 END
//persist employeeObjectInDatabase as it has the updated information
}
}