Search code examples
javahibernatespring-bootjpa

getting infinite recursion with JPA hibernate by @OneToMany and @ManyToOne


I have a problem that I can't solve, I tried it with JsonIgnore too, but it didn't work either. I have a ToDo list, and I want my tasks to output the UserID I gave to them. The problem is because every user has a Task array, the tasks are giving me an infinite loop of tasks and users.

enter image description here

that's my Code:

User:

@Entity
public class User {

@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private int id;

private String name;

@OneToMany(mappedBy = "user", cascade = CascadeType.ALL)
private Set<Task> tasks;

Task:

@Entity
public class Task {

@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private int id;

private String name;

@ManyToOne(fetch = FetchType.LAZY, optional = false)
@JoinColumn(name = "user_id", nullable = false)
private User user;

then I have normal getter and setter and a toString method.


Solution

  • I found the solution, i had to change my getUser() method to:

        public int getUser() {
        return user.getId();
    }
    

    now I get only the userId from the task and not everything from the User, that's why I don't get a recursion anymore.

    enter image description here

    I hope I can help now future people that have this problem too and don't find any solution on the internet