我使用Spring Boot和Spring HATEOAS来构建REST API。
我有2个简单的对象。让我们说:
// Model
@Entity
public class Person {
private String name;
private Address address;
// ... usual methods omitted for brievity
}
@Entity
public class Address {
private String street;
private String city;
// ...
}
// Repository. It exposes directly a REST service
public interface PersonRepository extends PagingAndSortingRepository<Person, Long> {}
// Application entry point
@ComponentScan
@EnableAutoConfiguration
@EnableJpaRepositories
@Import(RepositoryRestMvcConfiguration.class)
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
这个简单的项目创建如下输出:
{
"_links": {
"self": {
"href": "http://localhost:8080/persons{?page,size,sort}",
"templated": true
}
},
"_embedded": {
"persons": [
{
"name": "Some name",
"_links": {
"self": {
"href": "http://localhost:8080/persons/1"
},
"address": {
"href": "http://localhost:8080/persons/1/address"
}
}
}
]
}
}
很好,但我希望应用程序直接在响应中发送Address对象。为了不必查询地址的URL。
类似的东西:
...
"persons": [
{
"name": "Some name",
"address": {
"street": "Some street name"
"city": "Some city name"
}
"_links": {
"self": {
"href": "http://localhost:8080/persons/1"
},
"address": {
"href": "http://localhost:8080/persons/1/address"
}
}
}
]
...
有没有配置呢?我在Spring HATEOAS docs中找不到任何关于它的配置。当仅使用常规Spring控制器时,这是默认行为。
答案 0 :(得分:1)
最新版本的Spring Data REST文档说明了excerpt projections。这提供了数据集合的备用默认视图。
您的用例是它最初设计的确切角度。
答案 1 :(得分:0)
删除AddressRepository接口,对象Address将嵌入在Person类的json中。但是无法通过ID获取地址