首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >RepositoryRestMvcConfiguration的ObjectMapper与Spring默认ObjectMapper?

RepositoryRestMvcConfiguration的ObjectMapper与Spring默认ObjectMapper?
EN

Stack Overflow用户
提问于 2016-12-15 18:39:27
回答 1查看 975关注 0票数 2

我使用RepositoryRestMvcConfiguration对rest存储库行为进行微调:

代码语言:javascript
复制
@Configuration
public class WebConfig extends RepositoryRestMvcConfiguration {
    @Override
    protected void configureRepositoryRestConfiguration(RepositoryRestConfiguration config) {
      config.setReturnBodyOnCreate(true);
}

缺点是扩展类引入了自己的ObjectMapper bean,导致描述了这里的糖果。建议的解决方法是使用扩展类将ObjectMapper bean标记为@Primary,但是RepositoryRestMvcConfiguration中的bean在序列化嵌套实体时有不同的行为。

让我们假设以下几点:

代码语言:javascript
复制
@Entity class Parent {
    @Id Long id;
    @OneToMany @JsonManagedReference List<Child> children;
    // usual getters and setters for fields...
}

@Entity class Child {
    @Id Long id;
    @ManyToOne @JsonBackReference Parent parent;
    @ManyToOne @JsonBackReference School school;
    public getSchooldId() { return school.getId(); }
    // usual getters and setters for fields...
}

@Entity class School {
    @Id Long id;
    @OneToMany @JsonManagedReference List<Child> children;
    // usual getters and setters for fields...
} 

使用默认的Spring,ObjectMapper提供了预期的结果(嵌套实体被呈现):

代码语言:javascript
复制
{"id": 1, "children":[{"id":2, "schoolId":7},{"id":3, "schooldId":8}]}

但是,来自ObjectMapper的RepositoryRestMvcConfiguration忽略了子实体:

代码语言:javascript
复制
{"id": 1}

配置RepositoryRestMvcConfiguration ObjectMapper以实现与Spring默认值相同的行为的正确方法是什么?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2016-12-20 12:56:26

RepositoryRestMvcConfiguration创建两个objectMapper对象。

  1. 内部框架使用的objectMapper。
  2. halObjectMapper负责呈现集合、Resources和链接。

通过使用限定符自动加载objectMapper,您可以尝试实现所需的结果:

代码语言:javascript
复制
@Qualifier('_halObjectMapper')

编辑:用于呈现关联/嵌套属性

Spring数据-rest在默认情况下不呈现关联( 参考文献 ),因为它们在HATE美洲组织规范(json的_link部分)下可用。如果您想呈现关联,只需使用Projections.

这个人有几个属性:id是主键,firstName和lastName是数据属性,address是另一个域对象的链接。

代码语言:javascript
复制
@Entity
public class Person {

  @Id @GeneratedValue
  private Long id;
  private String firstName, lastName;

  @OneToOne
  private Address address;
  …
}

将呈现:

代码语言:javascript
复制
   {
  "firstName" : "Frodo",
  "lastName" : "Baggins",
  "_links" : {
    "self" : {
      "href" : "http://localhost:8080/persons/1"
    },
    "address" : {
      "href" : "http://localhost:8080/persons/1/address"
    }
    }
    }

默认情况下,Spring将导出这个域对象,包括它的所有属性。firstName和lastName将作为它们本身的普通数据对象导出。关于address属性有两个选项。一种选择是也定义一个地址存储库。 还有另一条路。如果Address域对象没有自己的存储库定义,Spring数据REST将在Person资源中内联数据字段。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/41171145

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档