【发布时间】:2017-05-01 11:14:07
【问题描述】:
我正在使用 RepositoryRestMvcConfiguration 来微调其余存储库的行为:
@Configuration
public class WebConfig extends RepositoryRestMvcConfiguration {
@Override
protected void configureRepositoryRestConfiguration(RepositoryRestConfiguration config) {
config.setReturnBodyOnCreate(true);
}
缺点是扩展类引入了它自己的 ObjectMapper bean,导致here 中描述的冲突。推荐的解决方法是使用扩展类将 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 默认相同的行为的正确方法是什么?
【问题讨论】:
标签: java spring-boot jackson spring-data spring-data-rest