2015-09-08 5 views
0

Я использую Spring HATEOAS для создания API REST HATEOAS в моем приложении. Пока это работает, но я застрял, когда дело доходит до вложенных ресурсов. Что такое правильный подход для отображения иерархии классов, как это ресурс REST HATEOAS:REST HATEOAS: Как сериализовать вложенные ресурсы (с Spring HATEOAS)?

public class MyEntity { 

    private int id; 

    private List<ChildEntity> children; 

} 


public class ChildEntity { 

    private int id; 

    private AnotherEntity entity; 

} 


public class AnotherEntity { 
} 

я создал Resource классы для всех этих лиц, но когда serialising MyEntity, все содержащиеся в нем объекты получить сериализации, как POJOs хотя мне нужно их также можно сериализовать как ресурсы (со ссылками и т. д.). Есть ли способ добавить ресурс в родительский ресурс (и не использовать класс Resources)? Или мне нужно добавить @JsonIgnore для детей, а затем вручную добавить детей в качестве ресурсов в моем ResourceAssembler? Не имеет ли смысл использовать ResourceSupport вместо ресурса?

ответ

1

Расширение ResourceSupport:

public class MyEntityResource extends ResourceSupport { 

    private int identificator; 

    private List<ChildEntityResource> children; 

    public int getIdentificator() { 
     return identificator; 
    } 

    public void setIdentificator(int id) { 
     this.identificator = identificator; 
    } 

    public List<ChildEntityResource> getChildren() { 
     return children; 
    } 

    public void setChildren(List<ChildEntityResource> children) { 
     this.children = children; 
    } 

} 

public class ChildEntityResource extends ResourceSupport { 

    private int identificator; 

    private AnotherEntityResource entity; 

    public int getIdentificator() { 
     return identificator; 
    } 

    public void setIdentificator(int identificator) { 
     this.identificator = identificator; 
    } 

    public AnotherEntityResource getEntity() { 
     return entity; 
    } 

    public void setEntity(AnotherEntityResource entity) { 
     this.entity = entity; 
    } 
} 

public class AnotherEntityResource extends ResourceSupport { 

    private String value; 


    public String getValue() { 
     return value; 
    } 

    public void setValue(String value) { 
     this.value = value; 
    } 
} 

@RestController 
public class EntityController { 
    @RequestMapping(value = "/entity", method = RequestMethod.GET) 
    public ResponseEntity<MyEntityResource> index() { 

     AnotherEntityResource anotherEntityResource = new AnotherEntityResource(); 
     anotherEntityResource.add(new Link("link-for-another-entity-resource", "rel-1")); 

     anotherEntityResource.setValue("value for Another Entity","rel-2"); 

     ChildEntityResource childEntityResource = new ChildEntityResource(); 
     childEntityResource.setIdentificator(20); 
     childEntityResource.setEntity(anotherEntityResource); 
     childEntityResource.add(new Link("link-for-child-entity-resource", "rel-3")); 

     MyEntityResource entityResource = new MyEntityResource(); 

     entityResource.setIdentificator(100); 
     entityResource.setChildren(Arrays.asList(childEntityResource)); 
     entityResource.add(new Link("link-for-entity-resource")); 

     return new ResponseEntity<MyEntityResource>(entityResource, HttpStatus.OK); 
    } 

} 

@SpringBootApplication 
public class Application { 

    public static void main(String[] args) { 
     SpringApplication.run(Application.class, args); 
    } 

} 

Результат:

{ 
    "identificator": 100, 
    "children": [ 
     { 
      "identificator": 20, 
      "entity": { 
       "value": "value for Another Entity", 
       "_links": { 
        "rel-1": { 
         "href": "link-for-another-entity-resource" 
        } 
       } 
      }, 
      "_links": { 
       "rel-2": { 
        "href": "link-for-child-entity-resource" 
       } 
      } 
     } 
    ], 
    "_links": { 
     "rel-3": { 
      "href": "link-for-entity-resource" 
     } 
    } 
} 

Но вы должны учитывать, если это правильный выбор для подключения различных ресурсов. Если вы не предложите в контроллерах методы получить эти встроенные ресурсы, вы не сможете достичь их индивидуально. Одним из решений для этого является использование HAL. С помощью HAL вы можете указать ресурс с помощью свойства _links или встроить эти ресурсы в свойство _embedded.

Смежные вопросы