복붙노트

[SPRING] Spring 데이터 Rest 기능으로 사용자 정의 Spring MVC HTTP 패치 요청

SPRING

Spring 데이터 Rest 기능으로 사용자 정의 Spring MVC HTTP 패치 요청

커스텀 Spring MVC 컨트롤러에서 HTTP PATCH를 지원하는 가장 좋은 방법은 무엇입니까? 특히 HATEOAS / HAL을 사용할 때? 요청 json (또는 DTO 작성 및 유지)에서 모든 단일 필드의 존재 여부를 확인하지 않고도 객체를 병합하는 더 쉬운 방법이 있습니까? 이상적으로는 자원에 대한 링크의 자동 비 정렬 화가 이상적입니까?

이 기능이 스프링 데이터 레스트에 존재한다는 것을 알고 있지만 이것을 커스터마이징 컨트롤러에서 사용할 수 있습니까?

해결법

  1. ==============================

    1.스프링 데이터 휴식 기능을 여기에서 사용할 수 있다고 생각하지 않습니다.

    스프링 데이터 휴식 기능을 여기에서 사용할 수 있다고 생각하지 않습니다.

    spring-data-rest는 json-patch 라이브러리를 내부적으로 사용하고 있습니다. 기본적으로 워크 플로는 다음과 같을 것이라고 생각합니다.

    나는 어려운 부분이 네 번째 요점이라고 생각한다. 그러나 일반적인 솔루션을 가질 필요가 없다면 더 쉬울 수 있습니다.

    spring-data-rest가하는 일에 대한 인상을 원한다면 org.springframework.data.rest.webmvc.config.JsonPatchHandler를 보라.

    편집하다

    최신 realeases에서 spring-data-rest의 패치 메커니즘이 크게 변경되었습니다. 가장 중요한 점은 더 이상 json-patch 라이브러리를 사용하지 않고 처음부터 json 패치 지원을 구현하고 있다는 것입니다.

    커스텀 컨트롤러 방식에서 주 패치 기능을 재사용 할 수있었습니다.

    다음 스 니펫은 spring-data-rest 2.6을 기반으로 한 접근법을 보여줍니다.

            import org.springframework.data.rest.webmvc.IncomingRequest;
            import org.springframework.data.rest.webmvc.json.patch.JsonPatchPatchConverter;
            import org.springframework.data.rest.webmvc.json.patch.Patch;
    
            //...
            private final ObjectMapper objectMapper;
            //...
    
            @PatchMapping(consumes = "application/json-patch+json")
            public ResponseEntity<Void> patch(ServletServerHttpRequest request) {
              MyEntity entityToPatch = someRepository.findOne(id)//retrieve current state of your entity/object to patch
    
              Patch patch = convertRequestToPatch(request);
              patch.apply(entityToPatch, MyEntity.class);
    
              someRepository.save(entityToPatch);
              //...
            }      
    
            private Patch convertRequestToPatch(ServletServerHttpRequest request) {  
              try {
                InputStream inputStream =  new IncomingRequest(request).getBody();
                return new JsonPatchPatchConverter(objectMapper).convert(objectMapper.readTree(inputStream));
              } catch (IOException e) {
                throw new UncheckedIOException(e);
              }
            }
    
  2. from https://stackoverflow.com/questions/33288670/custom-spring-mvc-http-patch-requests-with-spring-data-rest-functionality by cc-by-sa and MIT license