我有一些JPA機型:「類別」和「文章」:春傑克遜:集JSON動態忽略
@Entity
@Table(name = "categories")
public class Category {
private int id;
private String caption;
private Category parent;
private List<Category> childrenList;
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
@Column
public String getCaption() {
return caption;
}
public void setCaption(String caption) {
this.caption = caption;
}
@ManyToOne
@JoinColumn(name = "parent_id")
public Category getParent() {
return parent;
}
public void setParent(Category parent) {
this.parent = parent;
}
@OneToMany
@JoinColumn(name = "parent_id")
public List<Category> getChildrenList() {
return childrenList;
}
public void setChildrenList(List<Category> childrenList) {
this.childrenList = childrenList;
}
}
@Entity
@Table(name = "articles")
public class Article {
private int id;
private String caption;
private boolean isAvailable;
private String description;
private int price;
private Category category;
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
@Column
public String getCaption() {
return caption;
}
public void setCaption(String caption) {
this.caption = caption;
}
@Column(name = "is_available")
@Type(type = "org.hibernate.type.NumericBooleanType")
public boolean getIsAvailable() {
return isAvailable;
}
public void setIsAvailable(boolean available) {
isAvailable = available;
}
@Column
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
@Column
public int getPrice() {
return price;
}
public void setPrice(int price) {
this.price = price;
}
@ManyToOne
@JoinColumn(name = "category_id")
public Category getCategory() {
return category;
}
public void setCategory(Category category) {
this.category = category;
}
}
我也有一些REST控制器有兩個方法: 1)在第一種方法我需要獲取並序列化最近的10篇文章,但在Categegory中我不需要「childrenList」和「parent」字段。 2)在第二種方法中,我需要獲得相同的序列化「父」字段。
我該如何解決這個問題? 如果我將使用@JsonIgnore註釋到這些字段,那麼他們將永遠不會被序列化。 或者我應該使用DTO類嗎?
如何動態設置字段忽略?
歡迎來到Stack Overflow!我會想象這95%的代碼與你的問題無關。請創建一個[**最小**,完整且可驗證的示例](http://stackoverflow.com/help/mcve),以說明您的問題。 –