如何管理相互链接的实体的序列化?
How to manage serializataion of Entities that have links to each other?
我有一个 投票 和一个 餐厅 实体,当我管理它们与
@JsonBackReference
和 @JsonManagedReference
我有问题。
如果我连载 Restaurant - 一切似乎都很好。
如果我序列化 Vote - @JsonManagedReference
的字段将被省略。我有这个 JSON:
{
"id": 50,
"voteDate": "2021-08-04"
}
如果你能告诉我,我将不胜感激,我如何在不遗漏字段和得到 Whosebug
错误的情况下序列化两个对象。
为简洁起见,省略了一些实体的代码:
@Entity
public class Vote extends AbstractBaseEntity {
@ManyToOne
@JsonBackReference
private Restaurant restaurant;
private LocalDate voteDate;
@ManyToOne(fetch = FetchType.LAZY)
@JsonBackReference
private User user;
}
@Entity
@Getter
@Setter
@NoArgsConstructor
@ToString(exclude = {"votes", "dishes"})
public class Restaurant extends AbstractNamedEntity {
String address;
@OneToMany(mappedBy = "restaurant", cascade = CascadeType.ALL, orphanRemoval = true)
@JsonManagedReference
private List<Dish> dishes;
@OneToMany(mappedBy = "restaurant", cascade = CascadeType.ALL, orphanRemoval = true)
@JsonManagedReference
private List<Vote> votes;
}
您必须将实体转换为 DTO 对象。将后缀 Entity
添加到实体。并为 DTO 使用不带后缀的名称。
@Entity
class VoteEntity {
}
class Vote {
private String voteDate;
private String restaurantName;
}
在服务级别将实体转换为 DTO,然后进行序列化。
我有一个 投票 和一个 餐厅 实体,当我管理它们与
@JsonBackReference
和 @JsonManagedReference
我有问题。
如果我连载 Restaurant - 一切似乎都很好。
如果我序列化 Vote - @JsonManagedReference
的字段将被省略。我有这个 JSON:
{
"id": 50,
"voteDate": "2021-08-04"
}
如果你能告诉我,我将不胜感激,我如何在不遗漏字段和得到 Whosebug
错误的情况下序列化两个对象。
为简洁起见,省略了一些实体的代码:
@Entity
public class Vote extends AbstractBaseEntity {
@ManyToOne
@JsonBackReference
private Restaurant restaurant;
private LocalDate voteDate;
@ManyToOne(fetch = FetchType.LAZY)
@JsonBackReference
private User user;
}
@Entity
@Getter
@Setter
@NoArgsConstructor
@ToString(exclude = {"votes", "dishes"})
public class Restaurant extends AbstractNamedEntity {
String address;
@OneToMany(mappedBy = "restaurant", cascade = CascadeType.ALL, orphanRemoval = true)
@JsonManagedReference
private List<Dish> dishes;
@OneToMany(mappedBy = "restaurant", cascade = CascadeType.ALL, orphanRemoval = true)
@JsonManagedReference
private List<Vote> votes;
}
您必须将实体转换为 DTO 对象。将后缀 Entity
添加到实体。并为 DTO 使用不带后缀的名称。
@Entity
class VoteEntity {
}
class Vote {
private String voteDate;
private String restaurantName;
}
在服务级别将实体转换为 DTO,然后进行序列化。