I am new at spring boot JPA. I am trying the examples described here:
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 :)