我正在开发一个 Spring boot(MVC、JPA)应用程序,它需要在不同的请求上返回不同的属性。我找到了 @JsonView 注释,它似乎有效。但是我需要用基本 View 来注释每个属性吗?
示例:
实体 1
@Entity
public class Entity1 implements Serializable {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@JsonView(JsonViews.ExtendedView.class)
private String name;
@OneToMany(cascade = CascadeType.ALL, mappedBy = "entity1", fetch = FetchType.EAGER)
List<Entity2> entities2;
@JsonView(JsonView.ExtendedView.class)
@OneToMany(cascade = CascadeType.ALL, mappedBy = "entity1", fetch = FetchType.LAZY)
List<Entity3> entities3;
}
实体2
@Entity
public class Entity2 implements Serializable {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String name;
}
实体3
@Entity
public class Entity3 implements Serializable {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String name;
}
观看次数
public class JsonViews {
public static class BasicView { }
public static class ExtendedView extends BasicView { }
}
Controller
@RequestMapping(method = RequestMethod.GET)
@JsonView(JsonViews.BasicView.class)
public @ResponseBody List<Entity1> index() {
return repositoryEntity1.findAll();
}
这是一个修剪过的例子,但我认为它适用于这个问题。我希望 Controller 返回 ID 和 Entity2
对象列表。但它返回一个具有“无属性”的空对象。如果我注释这个请求中涉及的每个类的每个属性,它似乎可以工作,但这真的是必需的还是最好的解决方案?有没有办法定义“DefaultView”?
谢谢
编辑:如果我注释 JpaRepository,它会返回整个对象,包括带有 Entity3 对象的列表。
最佳答案
不,您不需要定义所有属性的 View 。插入
spring.jackson.mapper.default-view-inclusion=true
在您的 application.properties
中。这将导致没有 @JsonView
注释的属性被包含在响应中,并且只有注释的属性将被过滤。
在您的 Controller 中,没有 View 或带有 BasicView
注释的属性将被返回。
关于java - JsonView - 定义默认 View ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28813762/