简体   繁体   中英

Spring Boot JPA StackOverflowError

I am new at spring boot JPA. I am trying the examples described here:

https://en.wikibooks.org/wiki/Java_Persistence/OneToMany#Example_of_a_OneToMany_relationship_database

so I have defined the two entities:

@Entity
public class Employee {
  @Id
  @Column(name="EMP_ID")
  private long id;
  ...
  @OneToMany(mappedBy="owner")
  private List<Phone> phones;
  ...
}

and:

@Entity
public class Phone {
  @Id
  private long id;
  ...
  @ManyToOne(fetch=FetchType.LAZY)
  @JoinColumn(name="OWNER_ID")
  private Employee owner;
  ...
}

(an employee can have more than one phone number, work, home, etc.). The problem is that, when I try to list the Employee instances with my entityManager:

public List<Employee> getAll() 
{
    return entityManager.createQuery("from Employee").getResultList();
}

I got a spring StackOverflowError. Actually I am trying to refer Employee, which includes a list of Phone(s), but a Phone refers an Employee back so is it not a recursion? I feel as I am missing something about bi-directional associations (uni-directional associations worked fine) .. how can I have an entity A which refer B, being B referring A, and got a JSON response correctly from spring? Can someone point me in the right direction?

I found this workaround:

Infinite Recursion with Jackson JSON and Hibernate JPA issue

using @JsonManagedReference and @JsonBackReference I can tell Jackson not to serialize one side on my association and it works! But the final result is a unidirectional association (I can see the list of phones on the employee entity, but not the employee on every phone instance). So what is the purpose of bi-directional association if I have to cut one side of them in order to have my code working? Very confused :)

I believe Hibernate can manage this bi-directional association pretty well. It's only when Jackson tries to build the JSON from your object structure, it goes into recursion.

If you are using @Data in your entity then try to override the toString method.

I have faced the same issue but after overriding the toString method it got resolved. May be toString creates circular dependency while converting.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM