【问题标题】:Spring HATEOAS, embed linked object in WS responseSpring HATEOAS,在 WS 响应中嵌入链接对象
【发布时间】:2014-09-29 17:04:50
【问题描述】:

我正在使用 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"
                    }
                }
            }
        ]
    }
}

很好,但我希望应用程序直接在响应中发送地址对象。为了不用查询地址的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 控制器时的默认行为。

【问题讨论】:

  • 地址是否用@Entity 注释?
  • @ChrisDaMour 是的。我忘记了,我已经编辑了我的问题以添加它们

标签: java spring spring-boot spring-hateoas


【解决方案1】:

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

您的用例正是它最初设计的角度。

【讨论】:

  • 我无法测试,但我标记为正确答案,因为这正是我当时所需要的
【解决方案2】:

删除AddressRepository接口,对象Address将嵌入到Person类的json中。但是无法通过 ID 获取地址

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-04-14
    • 2016-05-23
    • 2014-11-06
    • 1970-01-01
    • 2023-03-28
    • 1970-01-01
    相关资源
    最近更新 更多