Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to update only attributes that have changed - Spring MVC

My controller

@RequestMapping(value = "/user/{id}", method = RequestMethod.GET)
public String updateUserById(@PathVariable("id") Long id, Model model) {
    User user = userRepository.findOne(id);
    model.addAttribute(user);
    return "admin/editUser";
}

@RequestMapping(value = "/user/{id}", method = RequestMethod.POST)
@ResponseBody
public String updateUserById(@PathVariable("id") Long id, @ModelAttribute User user) {
    userRepository.updateUser(id, user); // with a try catch
}

The dao

@Override
public void updateUser(Long id, User user) {
    User userDB = userRepository.findOne(id);
    userDB.setFirstName(user.getFirstName());
    userDB.setLastName(user.getLastName());
    userDB.setEmail(user.getEmail());
    userDB.setUsername(user.getUsername());
    userRepository.save(userDB);
}

This method works but it's pretty ugly for me. Let's say that the user have just changed the firstname field in the view, how can I adapt my code to only call the function to set the firstname ?

Something like the Observer pattern to notify field that have change ?

like image 212
melkir Avatar asked Feb 12 '16 07:02

melkir


2 Answers

if you are using hibernate then there is one attribute in hibernate dynamicUpdate = true which will update only updated fields in db

like below code

@Entity
@Table(name = "User")
@org.hibernate.annotations.Entity(
        dynamicUpdate = true
)
public class User 

for hibenrate 4 + use these

@DynamicInsert(true)
@DynamicUpdate(true)
like image 126
Musaddique Avatar answered Nov 18 '22 15:11

Musaddique


I suppose that your code works like this:

An user want to change some data of his user entity. Means in frontend you already show him all his entries from the user table of the DB like firstname, lastname and so on.

For example the user changed his firstname and hit the save button. Your controller receive the user entity inclusive the user.id, the new firstname and all the old set values. If your code works like this you can easily save() the user entity. There is no need to fetch the user from the DB first.

So just do it like this:

@Override
public void updateUser(User user) {
    userRepository.save(user);
}

The Repository knows the Id of the user entity and just update the complete entity.

And for the reason you dont have the Id in your user entity use the Id from your controller like this:

@Override
public void updateUser(User user, Long Id) {
    user.setId(Id);
    userRepository.save(user);
}
like image 34
Patrick Avatar answered Nov 15 '22 13:11

Patrick