Spring Partial Update Object Data Binding

后端 未结 8 1769
挽巷
挽巷 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 08:58

    I've done this with a java Map and some reflection magic:

    public static Entidade setFieldsByMap(Map dados, Entidade entidade) {
            dados.entrySet().stream().
                    filter(e -> e.getValue() != null).
                    forEach(e -> {
                        try {
                            Method setter = entidade.getClass().
                                    getMethod("set"+ Strings.capitalize(e.getKey()),
                                            Class.forName(e.getValue().getClass().getTypeName()));
                            setter.invoke(entidade, e.getValue());
                        } catch (Exception ex) { // a lot of exceptions
                            throw new WebServiceRuntimeException("ws.reflection.error", ex);
                        }
                    });
            return entidade;
        }
    

    And the entry point:

        @Transactional
        @PatchMapping("/{id}")
        public ResponseEntity partialUpdate(@PathVariable String entity,
                @PathVariable Long id, @RequestBody Map data) {
            // ...
            return new ResponseEntity<>(obj, HttpStatus.OK);
        }
    

提交回复
热议问题