Spring Partial Update Object Data Binding

后端 未结 8 1777
挽巷
挽巷 2020-12-02 08:26

We are trying to implement a special partial update function in Spring 3.2. We are using Spring for the backend and have a simple Javascript frontend. I\'ve not been able to

8条回答
  •  北荒
    北荒 (楼主)
    2020-12-02 09:00

    Following approach could be used.

    For this scenario, PATCH method would be more appropriate since the entity will be partially updated.

    In controller method, take the request body as string.

    Convert that String to JSONObject. Then iterate over the keys and update matching variable with the incoming data.

    import org.json.JSONObject;
    
    @RequestMapping(value = "/{id}", method = RequestMethod.PATCH )
    public ResponseEntity updateUserPartially(@RequestBody String rawJson, @PathVariable long id){
    
        dbUser = userRepository.findOne(id);
    
        JSONObject json = new JSONObject(rawJson);
    
        Iterator it = json.keySet().iterator();
        while(it.hasNext()){
            String key = it.next();
            switch(key){
                case "displayName":
                    dbUser.setDisplayName(json.get(key));
                    break;
                case "....":
                    ....
            }
        }
        userRepository.save(dbUser);
        ...
    }
    

    Downside of this approach is, you have to manually validate the incoming values.

提交回复
热议问题