【发布时间】:2015-05-03 00:56:34
【问题描述】:
我正在开发一个 Spring Boot(MVC、JPA)应用程序,它需要在不同的请求上返回不同的属性。我找到了 @JsonView 注释,它似乎工作。但是我需要用基本视图注释每个属性吗?
例子:
实体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;
}
Entity2
@Entity
public class Entity2 implements Serializable {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String name;
}
Entity3
@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 { }
}
控制器
@RequestMapping(method = RequestMethod.GET)
@JsonView(JsonViews.BasicView.class)
public @ResponseBody List<Entity1> index() {
return repositoryEntity1.findAll();
}
这是一个精简的示例,但我认为它适用于该问题。我希望控制器返回 ID 和 Entity2 对象列表。但它返回一个“无属性”的空对象。如果我注释此请求中涉及的每个类的每个属性,它似乎可以工作,但这真的需要还是最好的解决方案?有没有办法定义一个“DefaultView”?
谢谢
编辑:如果我对 JpaRepository 进行注释,它会返回整个对象,包括带有 Entity3 对象的列表。
【问题讨论】:
-
是的,您确实需要将其添加到每个变量中
-
请查看您的帖子。
标签: java spring jpa jackson spring-boot