我使用RepositoryRestMvcConfiguration对rest存储库行为进行微调:
@Configuration
public class WebConfig extends RepositoryRestMvcConfiguration {
@Override
protected void configureRepositoryRestConfiguration(RepositoryRestConfiguration config) {
config.setReturnBodyOnCreate(true);
}缺点是扩展类引入了自己的ObjectMapper bean,导致描述了这里的糖果。建议的解决方法是使用扩展类将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,ObjectMapper提供了预期的结果(嵌套实体被呈现):
{"id": 1, "children":[{"id":2, "schoolId":7},{"id":3, "schooldId":8}]}但是,来自ObjectMapper的RepositoryRestMvcConfiguration忽略了子实体:
{"id": 1}配置RepositoryRestMvcConfiguration ObjectMapper以实现与Spring默认值相同的行为的正确方法是什么?
发布于 2016-12-20 12:56:26
RepositoryRestMvcConfiguration创建两个objectMapper对象。
Resources和链接。通过使用限定符自动加载objectMapper,您可以尝试实现所需的结果:
@Qualifier('_halObjectMapper')编辑:用于呈现关联/嵌套属性
Spring数据-rest在默认情况下不呈现关联( 参考文献 ),因为它们在HATE美洲组织规范(json的_link部分)下可用。如果您想呈现关联,只需使用Projections.
这个人有几个属性: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将导出这个域对象,包括它的所有属性。firstName和lastName将作为它们本身的普通数据对象导出。关于address属性有两个选项。一种选择是也定义一个地址存储库。 还有另一条路。如果Address域对象没有自己的存储库定义,Spring数据REST将在Person资源中内联数据字段。
https://stackoverflow.com/questions/41171145
复制相似问题