I currently have two ways to update Model, but neither feels very good:
< H2 > method 1: < / H2 > there is a WebApi project for SpringBoot that initiates a http request from the front end to update the Model.
for example, to update a User {id,name,age,nickName} entity with id 1, I only passed a User entity json from the front end to update nickName: {id:1,nickName:"young"}. After receiving such an entity at the back end, I updated it like this:
var user=userService.getById(model.id);
if(model.name!=null){
user.name=model.name;
}
if(model.age!=null){
user.age=model.age;
}
if(model.nickName!=null){
user.nickName=model.nickName;
}
userService.update(user);
- disadvantage: from the above example, it is obvious that this kind of coding is too bad. If the User class has 100 attributes, I want if to judge it 100 times!
Mybatis, a updateBySelective () method can be generated through the Generator tool, which can automatically complete such an operation on its own based on the value of the model passed in.
for example, if you pass in an entity that contains a nickName attribute, it will automatically update it for you, otherwise it will not be updated. All you need to do is to call the method gracefully:
userService.update(model);
but there is also a problem with such a method:
if my business logic does not allow age, modification, but the current side has passed age, the age, will definitely be updated automatically. If I want to restrict updating age, I can only write:
if(model.age!=null){
model.age=null;
}
userService.update(model);
such code will also look ugly.
- disadvantage: if some attributes do not allow for more detail, you need to keep adding if statements.
is there a better way to solve the shortcomings of the above two methods and update Model? gracefully?