Skip to content
Advertisement

Spring REST partial update with @PATCH method

I’m trying to implement a partial update of the Manager entity based in the following:

Entity

public class Manager {
    private int id;
    private String firstname;
    private String lastname;
    private String username;
    private String password;

    // getters and setters omitted
}

SaveManager method in Controller

@RequestMapping(value = "/save", method = RequestMethod.PATCH)
public @ResponseBody void saveManager(@RequestBody Manager manager){
    managerService.saveManager(manager);
}

Save object manager in Dao impl.

@Override
public void saveManager(Manager manager) {  
    sessionFactory.getCurrentSession().saveOrUpdate(manager);
}

When I save the object the username and password has changed correctly but the others values are empty.

So what I need to do is update the username and password and keep all the remaining data.

Advertisement

Answer

You can write custom update query which updates only particular fields:

@Override
public void saveManager(Manager manager) {  
    Query query = sessionFactory.getCurrentSession().createQuery("update Manager set username = :username, password = :password where id = :id");
    query.setParameter("username", manager.getUsername());
    query.setParameter("password", manager.getPassword());
    query.setParameter("id", manager.getId());
    query.executeUpdate();
}
User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement