我有一些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),以说明您的问题。 –