【发布时间】:2017-05-19 08:02:41
【问题描述】:
我有一些 JPA 模型:“类别”和“文章”:
@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 篇文章,但我不需要类别中的“childrenList”和“parent”字段。 2)在第二种方法中,我需要获得相同但序列化“父”字段。
我该如何解决这个问题? 如果我将对这些字段使用@JsonIgnore 注释,那么它们将永远不会被序列化。 还是我应该使用 DTO 类?
如何动态设置忽略字段?
【问题讨论】:
-
欢迎来到 Stack Overflow!我想 95% 的代码与你的问题无关。请创建一个 Minimal, Complete and Verifiable Example 来证明您的问题。
标签: java json spring spring-mvc jackson