我在父对象 CommentTarget 中定义了以下内容:
// bi-directional many-to-one association to EmployerDetails
@OneToMany(mappedBy = "commentTarget", cascade = CascadeType.ALL, fetch = FetchType.EAGER)
private List<Comment> comments;
这在子评论中定义:
@ManyToOne(cascade = {CascadeType.DETACH, CascadeType.MERGE, CascadeType.PERSIST, CascadeType.REFRESH} )
@JoinColumn(name = "comment_target_id")
private CommentTarget commentTarget;
但是,当我从目标获取列表并以 JSON 形式返回时:
@RestController
@RequestMapping("/ticketV2")
public class TicketV2Controller {
@Autowired
CommentTargetService commentTargetService;
@RequestMapping(value = "/{ticketId}/comments", method = RequestMethod.GET)
public List<Comment> getTicketComments(@PathVariable(value="ticketId") String id,
@RequestParam String type){
CommentTarget commentTarget = commentTargetService.findByTargetIdAndTargetType(Long.valueOf(id), TargetName.valueOf(type));
List<Comment> commentsList = commentTarget.getComments();
return commentsList;
}
它会崩溃,因为它保留了对目标的引用,然后是其中的列表等等:
[
{
"id": 997,
"commentedBy": 1,
"commenterName": "Exchange Admin",
"comment": "123456",
"commentTarget": {
"id": 703,
"targetId": 216,
"targetName": "TICKET",
"created": 1586548428358,
"updated": 1586548428358,
"comments": [
{
"id": 997,
"commentedBy": 1,
"commenterName": "Exchange Admin",
"comment": "123456",
"commentTarget": {
"id": 703,
"targetId": 216,
"targetName": "TICKET",
"created": 1586548428358,
"updated": 1586548428358,
"comments": [
{
"id": 997,
"commentedBy": 1,
"commenterName": "Exchange Admin",
"comment": "123456",
"commentTarget": {
"id": 703,
"targetId": 216,
"targetName": "TICKET",
"created": 1586548428358,
"updated": 1586548428358,
"comments": [
{
"id": 997,
"commentedBy": 1,
"commenterName": "Exchange Admin",
"comment": "123456",
"commentTarget": {
"id": 703,
"targetId": 216,
"targetName": "TICKET",
"created": 1586548428358,
"updated": 1586548428358,
"comments": [
当只想返回子评论列表时,不知道如何分离两者之间的关系。
最佳答案
请注意:
- @JsonManagedReference 是引用的前向部分 - 那个 可以正常序列化。
- @JsonBackReference 是后面部分 引用 - 它将在序列化中被省略。
如下所示更改您的映射。
@OneToMany(mappedBy = "commentTarget", cascade = CascadeType.ALL, fetch = FetchType.EAGER)
@JsonManagedReference
private List<Comment> comments;
@ManyToOne
@JoinColumn(name = "comment_target_id")
@JsonBackReference
private CommentTarget commentTarget;
关于java - 子对象具有父对象作为属性 JPA 导致无尽的 JSON,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61356956/