繁体   English   中英

RepositoryRestMvcConfiguration的ObjectMapper与Spring Boot默认的ObjectMapper?

[英]RepositoryRestMvcConfiguration's ObjectMapper vs. Spring Boot default ObjectMapper?

我正在使用RepositoryRestMvcConfiguration来微调其余存储库的行为:

@Configuration
public class WebConfig extends RepositoryRestMvcConfiguration {
    @Override
    protected void configureRepositoryRestConfiguration(RepositoryRestConfiguration config) {
      config.setReturnBodyOnCreate(true);
}

缺点是扩展的类带来了自己的ObjectMapper豆,造成描述conficts 这里 推荐的解决方法是使用扩展类将ObjectMapper Bean标记为@Primary ,但是序列化嵌套实体时,来自RepositoryRestMvcConfiguration的Bean具有不同的行为。

让我们假设以下实体:

@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 Boot ObjectMapper可以得到预期的结果(呈现嵌套实体):

{"id": 1, "children":[{"id":2, "schoolId":7},{"id":3, "schooldId":8}]}

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

{"id": 1}

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

RepositoryRestMvcConfiguration创建两个objectMapper对象。

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

您可以尝试通过使用限定符自动装配objectMapper来获得所需的结果:

@Qualifier('_halObjectMapper')

编辑:用于渲染关联/嵌套的属性

Spring data-rest默认情况下不呈现关联( reference ),因为它们在HATEOAS规范(json的_link部分)下可用。 如果要渲染关联,则只需要使用Projections即可

此Person具有几个属性:id是主键,firstName和lastName是数据属性,address是到另一个域对象的链接

@Entity
public class Person {

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

  @OneToOne
  private Address address;
  …
}

将呈现:

   {
  "firstName" : "Frodo",
  "lastName" : "Baggins",
  "_links" : {
    "self" : {
      "href" : "http://localhost:8080/persons/1"
    },
    "address" : {
      "href" : "http://localhost:8080/persons/1/address"
    }
    }
    }

默认情况下,Spring Data REST将导出此域对象,包括其所有属性。 firstName和lastName将作为原始数据对象导出。 关于地址属性有两个选项。 一种选择是还定义地址的存储库。

还有另一条路线。 如果Address域对象没有其自己的存储库定义,则Spring Data REST将在Person资源内部内联数据字段。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM