Удалите связи ассоциаций для контента в коллекции ресурсов для Spring Data REST - PullRequest
1 голос
/ 16 июня 2019

Как настроить Spring Data REST для удаления ссылок на ассоциации сущностей (оставлено только "self") в ответе ресурса Collection Конечные точки интерфейса репозитория , без набора exported = false в аннотации @ResResource (необходимо сохранить экспортированные конечные точки)

У нас есть объекты, в которых часть _links имеет самый большой размер ответа:

  • Вкл. Ресурс элемента _ ссылки полезны для навигации по ассоциациям.

  • Но на Ресурсы сбора ,главным образом для больших коллекций, эта информация не важна и делает ответ ненужным больше.

Нам нужно изменить этот ответ:

    {
     "_embedded" : {
     "persons" : [ {
       "id" : "bat_3191",
       "name" : "B",
       "_links" : {     // 80% of response size !!
            "self" : {
                "href" : "http://localhost:8080/api/persons/bat_3191"
            },
            "orders" : {
                "href" : "http://localhost:8080/api/persons/bat_3191/order"
            },
            "payments" : {
                "href" : "http://localhost:8080/api/persons/bat_3191/payments"
            },
            "childrens" : {
                "href" : "http://localhost:8080/api/persons/bat_3191/childrens"
            },
            "invoices" : {
                "href" : "http://localhost:8080/api/persons/bat_3191/invoices"
            },
            "brands" : {
                "href" : "http://localhost:8080/api/persons/bat_3191/brands"
            },
        }
      },
      { person [2] } 
        ... 
      { person [N] }
      ]
    },
      "_links" : {
       [page links]
    }

Только на "себя"на _links часть:

{
"_embedded" : {
"persons" : [ {
  "id" : "bat_3191",
  "name" : "B",
  "_links" : {
    "self" : {
      "href" : "http://localhost:8080/api/persons/bat_3191"
    }
  }
}, {
  "id" : "bat_2340",
  "name" : "B",
  "_links" : {
    "self" : {
      "href" : "http://localhost:8080/api/persons/bat_2340"
    }
  }

1 Ответ

0 голосов
/ 19 июня 2019

Если я хотел управлять ссылками hateos в springboot, я использовал ассемблер ресурсов.Как пример:

@Autowired
private EmployeeAddressResourceAssembler assembler;

@GetMapping(value="/{empId}", produces=MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<EmployeeAddressResource> getEmployeeAddress(@PathVariable Integer empId) {
    EmployeeAddressItem employeeAddressItem = restTemplate.getForObject( 
        serviceUrl + "/employee/address/{empId}", 
        EmployeeAddressItem.class, empId);
    return ResponseEntity.ok( assembler.toResource(employeeAddressItem) );
}

А потом я использовал ассемблер ресурсов.

@Component
public class EmployeeAddressResourceAssembler
        extends ResourceAssemblerSupport<EmployeeAddressItem, EmployeeAddressResource> {

    public EmployeeAddressResourceAssembler() {
        super(EmployeeAddressController.class, EmployeeAddressResource.class);
    }

    @Override
    public EmployeeAddressResource toResource(EmployeeAddressItem item) {

        // createResource(employeeAddressItem);
        EmployeeAddressResource resource = createResourceWithId(item.getEmpId(), item);
        resource.fromEmployeeAddressItem(item);
        // … do further mapping
        resource.add(linkTo(methodOn(EmployeeAddressController.class).deleteEmployeeAddress(item.getEmpId())).withRel("delete"));        
        return resource;
    }

}

, а ResourceAssembler использует Resource

public class EmployeeAddressResource extends ResourceSupport {
    private Integer empId;
    private String address1;
    private String address2;
    private String address3;
    private String address4;
    private String state;
    private String country;

    public void fromEmployeeAddressItem(EmployeeAddressItem item) {
        this.empId = item.getEmpId();
        this.address1 = item.getAddress1();
        this.address2 = item.getAddress2();
        this.address3 = item.getAddress3();
        this.address4 = item.getAddress4();
        this.state = item.getState();
        this.country = item.getCountry();
    }

Все это в RestPracticeWithHateos

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...