2
我正在使用Spring引导(MVC,JPA)应用程序,它需要在不同的请求上返回不同的属性。我发现@JsonView注释,它似乎工作。但是,我是否需要使用基本视图注释每个属性?JsonView - 定义默认视图
实施例:
ENTITY1
@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对象列表中的全部对象。
是的,你需要将其添加到每个变量 – LynAs 2015-03-02 18:41:38
请检查您的帖子。 – Byeon0gam 2016-08-16 01:12:15