2014-09-29 44 views
1

我使用Spring Boot和Spring HATEOAS来构建REST API。Spring HATEOAS,在WS响应中嵌入链接对象

我有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" 
        } 
       } 
      } 
     ] 
    } 
} 

很好,但我想直接发送响应地址对象的应用程序。为了不必查询地址的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文档中找不到关于它的任何配置。这是仅使用常规Spring控制器时的默认行为。

+0

是用@Entity注释的地址吗? – 2014-10-07 20:56:39

+0

@ChrisDaMour是的。我忘记了,我编辑了我的问题添加它们 – Bertrand88 2014-10-09 16:41:18

回答

1

Spring Data REST文档的最新版本说明了excerpt projections。这提供了数据集合的替代默认视图。

您的使用案例是最初为其设计的确切角度。

+0

我无法测试,但我标记为正确的答案,因为它正是我当时所需要的 – Bertrand88 2016-03-30 15:05:23

0

删除AddressRepository接口,并将对象Address嵌入到Person类中的json中。但不可能通过ID获得地址