JPA一对多关系的toString()函数引发StackOverflowError [英] toString() function for JPA one-to-many relations raises StackOverflowError

查看:1021
本文介绍了JPA一对多关系的toString()函数引发StackOverflowError的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个JPA实体类,Task和TaskList。 TaskList和Task之间存在一对多关系(显然)与任务表中的 tasklist_id 外键之间存在一对多关系。

I have two JPA Entity classes, Task and TaskList. There's a one-to-many relationship between TaskList and Task (obviously) with the tasklist_id foreign key in the task table.

任务类是这样的:

@Entity(name = "task")
public class Task implements Serializable {    

    // Id and 3 fields

    @ManyToOne
    @JoinColumn(name="tasklist_id")
    private TaskList parentList;

    // 3 more fields

    // Constructor
    public Task() {}

    //Getters and Setters
}

TaskList 类是这个:

@Entity(name = "task_list")
public class TaskList implements Serializable {

    // Id and two fields

    @OneToMany(mappedBy="parentList")
    private List<Task> tasks;

    // Constructor
    public TaskList() {}
}

当我尝试将自动getter和setter添加到这两个类和toString()函数时,我得到一个StackOverflowError。

When I try to add an automatic getter and setter to these two classes and a toString() function, I get a StackOverflowError.

我该如何去关于为两个字段编写getter和setter以便我得到一个适当的对象 toString()

How do I go about writing getters and setters for the two fields so that I get a proper object with toString()?

推荐答案

对于未来的读者,解决方案是使用反向引用:

任务类:

@Entity(name = "task")
public class Task implements Serializable {    

    // Id and 3 fields

    @JsonBackReference("task_list-task")
    @ManyToOne
    @JoinColumn(name="tasklist_id")
    private TaskList parentList;

    // 3 more fields

    // Constructor
    public Task() {}

    //Getters and Setters
}

TaskList类

@Entity(name = "task_list")
public class TaskList implements Serializable {

    // Id and two fields

    @JsonManagedReference("task_list-task")
    @OneToMany(mappedBy="parentList")
    private List<Task> tasks;

    // Constructor
    public TaskList() {}
}



查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆