我有一些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条文章,但在Categegory中不需要“ childrenList”和“ parent”字段。2)在第二种方法中,我需要获取相同的内容,但是序列化“ parent”字段。
我该如何解决?如果我将对这些字段使用@JsonIgnore批注,那么它们将永远不会序列化。还是我应该使用DTO类?
如何动态设置要忽略的字段?
我从不使用我的Entitys来生成JSON,从长远来看,我认为另一组DTO类会让您更快乐。我的DTO通常具有一个将Entity作为参数的构造函数(如果打算使用它来解析传入的JSON,它仍然需要一个默认构造函数)。
如果您确实想使用实体,我建议您使用MixIns,它允许您注册MixIn类,从而增强了特定类的序列化。
这是我为另一个答案制作的MixIn示例的链接。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句