所以你想要两件事:
1)摆脱_links
领域
2)包括相关sector
领域
可能的解决方案(对我有用:D)
1)摆脱_links
为此创建以下类:
[... package declaration, imports ...]
public class MyRepositoryRestMvcConfiguration extends RepositoryRestMvcConfiguration {
public MyRepositoryRestMvcConfiguration(ApplicationContext context, ObjectFactory<ConversionService> conversionService) {
super(context, conversionService);
}
@Bean
protected LinkCollector linkCollector() {
return new LinkCollector(persistentEntities(), selfLinkProvider(), associationLinks()) {
public Links getLinksFor(Object object, List<Link> existingLinks) {
return new Links();
}
};
}
}
并使用它,例如:
[... package declaration, imports ...]
@SpringBootApplication
@Import({MyRepositoryRestMvcConfiguration.class})
public class MyApplication {
public static void main(String[] args) {
SpringApplication.run(MyApplication.class, args);
}
}
我很确定(99%,但未经测试)你不需要这个类来删除_links
相关实体/实体,包括下一点 (2) 的显示方式。
2)包括相关sector
字段
为此,您可以使用摘录(特别是为此场景制作的)。因为 Spring 示例非常雄辩,在这里复制它很愚蠢,我将指出它:https ://docs.spring.io/spring-data/rest/docs/3.1.x/reference/html/#projections -excerpts.excerpting-commonly-accessed-data。
但为了记录和您的方便,我将粘贴 spring 示例的主要部分:
@Projection(name = "inlineAddress", types = { Person.class })
interface InlineAddress {
String getFirstName();
String getLastName();
Address getAddress();
}
请参阅Projection javadoc,这types
意味着投影类型绑定到的类型。摘录可以这样使用
:
@RepositoryRestResource(excerptProjection = InlineAddress.class)
interface PersonRepository extends CrudRepository<Person, Long> {}
为了得到这个(当也使用MyRepositoryRestMvcConfiguration时):
{
"firstName" : "Frodo",
"lastName" : "Baggins",
"address" : {
"street": "Bag End",
"state": "The Shire",
"country": "Middle Earth"
}
}
对你sector
来说,相当于address
.
最后的笔记
返回数组时,该_links
字段不会被删除(这样做太麻烦了);最后你会得到这样的东西:
{
"_embedded" : {
"persons" : [ {person1}, {person2}, ..., {personN} ]
},
"_links" : {
e.g. first, next, last, self, profile
},
"page" : {
"size" : 1,
"totalElements" : 10,
"totalPages" : 10,
"number" : 0
}
}
正如你所看到的,即使我们已经_links
删除了这仍然不够;一个人可能还想要_embedded
替换它,persons
这会导致代码的可维护性降低(太多的 spring 侵入式覆盖)。但是,如果一个人真的也想要这些,他应该开始检查RepositoryRestMvcConfiguration
and RepositoryEntityController.getCollectionResource
。
Spring 正在发展,所以我觉得有必要指出这至少适用于:
spring-data-rest-webmvc 3.1.3.RELEASE
或者,如果您更喜欢弹簧靴版本:
spring-boot-starter-parent 2.1.1.RELEASE