函数引发StackOverflowError

函数引发StackOverflowError

本文介绍了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() {}
}




  • 添加正确的注释。将ManagedReference添加到@OneToMany(父)和BackReference到@ManyToOne(子)。在表示的括号中写表名,用连字符分隔。

  • 这会自动处理无限递归,解决StackOverflowError问题。

    This takes care of the infinite recursion automatically, solving the StackOverflowError problem.

    一些链接:



    这篇关于JPA一对多关系的toString()函数引发StackOverflowError的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-05 01:21