I'm using spring boot for restful webservices, and I've many DTO and Model objects.
When doing post request, front end user is sending a DTO type object. Dto has mostly similar members of Model object. I'm checking the null constraint of each member in DTO object and if not then set the value to similar attributes of MODEL object.
I've briefly defined my case below,
class UserDto{
private String userid;
private String username;
private String dept;
public String getUserid() {
return userid;
}
public void setUserid(String userid) {
this.userid = userid;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getDept() {
return dept;
}
public void setDept(String dept) {
this.dept = dept;
}
}
And pojo
class User {
private String userid;
private String username;
private String dept;
//some constructors
........
public String getUserid() {
return userid;
}
public void setUserid(String userid) {
this.userid = userid;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getDept() {
return dept;
}
public void setDept(String dept) {
this.dept = dept;
}
}
I check every time like this, now I just want to know is there any consistent way to do this
if (userDto.getUserid()!= null)
user.setUserid(userDto.getUserid());
if (userDto.getUsername()!= null)
user.setUsername(userDto.getUsername());
I've already looked at this link What is the best way to know if all the variables in a Class are null? . This only tells that how to find the nullable members in an object, but in my case I want to find the not null member and copy to the another member in an object. ie if userDto.getUsername()!==null
then user.setUsername(userDto.getUsername())
. This is all I need.