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