So what I am having is a spring controller:
@Controller
@RequestMapping("/user")
public class UserController() {
@RequestMapping(value = "/edit/{id}", method = RequestMethod.PUT)
public @ResponseBody HTTPResponseDTO edit(@RequestBody String data, @PathVariable long id) {
// marshall data String to User entity
ObjectMapper mapper = new ObjectMapper();
User marshaledUser = mapper.readValue(data, User.class);
User databaseUser = session.get(id, User.class);
//hibernate things to save
...
// session.save(user);
}
The data string is in the following json format:
{"name":"value1",
"email":"value2",
"note":"value3"}
The responseDTO is something simple looks like:
{"result":"success"}
When the client is passing in a data json, it will only pass in the value that is being edited, e.g.:
{"email":"value2"}
in this case, other non-supplied fields will be treated as null.
however "note" is a nullable field, and a user is allowed to clear the "note" field - in my current design, when it is doing so, it will be something like:
{"note":null}
QUESTION 1: So here is my dilemma: how can I tell if a user is on purpose to set this to null, or it is null only because it is not passed in from the data string?
QUESTION 2: When the controller is receiving the data String, I will have an entity coming from this data, I will then query database by id to get the existing User object. what is the best practice to merge these two objects? Looking for what fields exist in the marshaledUser and setting those to the databaseUser looks like lots of repetitive jobs:
if (marshaledUser.name != null) {
databaseUser.name = marshaledUser.name;
}
if (marshaledUser.email != null) {
databaseUser.email = marshaledUser.email;
}
if (marshaledUser.note != null) { // refer to question 1...
databaseUser.note = marshaledUser.note;
}
An object can easiler have over 5 fields - 5 if statements of almost same thing looks not worth it.. What is the best practice to handle this?