添加关联链接到春季数据休息自定义暴露方法
您好我已经公开了一个自定义的@RepositoryRestController通过Spring数据公开一个自定义的方法休息该方法的代码如下所示
@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
@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;
}
Foo实体使用自定义存储库方法提供的数据进行渲染,但json表示形式不包含指向该实体关联的链接。有没有办法通过框架暴露这些关联,而无需编写自定义ResourceProcessor就像他们在春季数据休息的其他盒子表示一样。
最后,我解决了一些春天的数据休息代码。所以实现这个想法,我从AbstractRepositoryRestController这一节得到了如何使用PersistentEntityResourceAssembler和pagedResourcesAssembler的想法。
@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);
}
}
所以在使用restms方法中提供的PersistentEntityResourceAssembler后,我最终可以为我的自定义查询提供弹簧数据和HAl类型代表。代码如下
@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);
}
希望它可以帮助周围的人:)
链接地址: http://www.djcxy.com/p/89597.html上一篇: adding association links to spring data rest custom exposed method