Reputation: 611
I know this has been asked a lot of times, and the solution is pretty obvious, but in my case it doesn't really work, and I can't figure out how to solve it.
problem: Could not write JSON: Infinite recursion (StackOverflowError)
The setup is like this:
Employee belongs to a Department. (ManyToOne) Department has a Employee as Manager. (OneToOne)
I didn't want to have a @OneToMany List in Department so the owning side is missing. Employee has a Department object, but this is the Department it belongs to, not the Department he manages.
Employee.java
@Entity
@Table(name = "ts_employee")
//@JsonIdentityInfo(generator=ObjectIdGenerators.IntSequenceGenerator.class,property="@emp_id")
public class Employee extends AbstractEntity {
@ManyToOne
@JoinColumn(name = "dept_id")
@JsonManagedReference
private Department department;
... getters and setters
}
Department.java
@Entity
@Table(name = "ts_department")
//@JsonIdentityInfo(generator=ObjectIdGenerators.IntSequenceGenerator.class, property="@dept_id")
public class Department extends AbstractEntity {
@OneToOne
@JoinColumn (name = "manager_id")
@JsonBackReference
private Employee manager;
.. other fields.. getters and setters
}
AbstractEntity.java
@MappedSuperclass
public class AbstractEntity implements Serializable {
@Id
@GeneratedValue()
private Long id;
... getters and setters
}
I've tried both solutions:
@JsonBackReference + @JsonManagedReference I get rid of the StackOverflow, but the Department.manager is not serialized (@JsonBackReference), and not sent in the response, which in bad.
@JsonIdentityInfo(generator=ObjectIdGenerators.IntSequenceGenerator.class, property="@emp_id"), which doesn't seem to do anything, and StackOverflow is thrown in my face :(
How can I solve this, hopefully without modifying the model classes?
Thanks a lot :)
Upvotes: 1
Views: 3710
Reputation: 5837
The @JsonBackReference
wont be serialized.
If possible try to use @JsonIdentityInfo
over @JsonManagedReference
and @JsonBackReference
. Follow this link for documentation.
You can also try using @JsonIgnore
if you don't need to maintain the relationship further in the process.
Upvotes: 5