adding association links to spring data rest custom exposed method
Hi I have exposed a custom @RepositoryRestController to expose a custom method via Spring data rest the code for the method looks something like below
@RequestMapping(method = RequestMethod.GET, value = "/foo/rsqlsearch")
public @ResponseBody PagedResources<Resource<Foos>> findAllPaged(@RequestParam(value = "rsql") String rsql, Pageable pageable) {
Page<Foo> foos= fundRepository.searchByRsql(rsql, pageable);
return pagedResourcesAssembler.toResource(foos);
}
foo entity
@Entity
@Table(name = "FOO_TBL", schema = "F")
@Data
public class Foo implements Identifiable<String> {
@Id
@Column(name = "ID")
@Description("Id")
private String id;
// associations
@OneToMany(mappedBy = "foo", fetch = FetchType.LAZY)
private List<FooFriends> fooFriends;
@OneToMany(mappedBy = "foo", fetch = FetchType.LAZY)
private List<Marks> marks;
}
The Foo entity renders fine with the data coming out of the custom repository method .But the json representation does not include the links to the associations for the entity .Is there a way by which these associations can be exposed via the framework without writing custom ResourceProcessor like they do in other out of the box representations of spring data rest .
Finally this got solved by me loooking at some spring data rest code .So the idea to implement this I got from the AbstractRepositoryRestController this section which gave me an idea on how to use both PersistentEntityResourceAssembler and pagedResourcesAssembler together.
@SuppressWarnings({ "unchecked" })
protected Resources<?> toResources(Iterable<?> source, PersistentEntityResourceAssembler assembler,
Class<?> domainType, Link baseLink) {
if (source instanceof Page) {
Page<Object> page = (Page<Object>) source;
return entitiesToResources(page, assembler, domainType, baseLink);
} else if (source instanceof Iterable) {
return entitiesToResources((Iterable<Object>) source, assembler, domainType);
} else {
return new Resources(EMPTY_RESOURCE_LIST);
}
}
so after using both with PersistentEntityResourceAssembler available in the restm method I finally could give spring data rest HAl type representaiton for my custom queries .Code below
@RequestMapping(method = RequestMethod.GET, value = "/foo/rsqlsearch")
public @ResponseBody PagedResources<?> findAllPaged(@RequestParam(value = RSQL_REL) String rsql,
Pageable pageable,
PersistentEntityResourceAssembler eass) {
Page<Object> entities = (Page<Object>) repository.searchByRsql(rsql, pageable);
return assembler.toResource(entities, eass);
}
Hope it helps people around :)
链接地址: http://www.djcxy.com/p/89598.html下一篇: 添加关联链接到春季数据休息自定义暴露方法