简体   繁体   中英

Spring MVC + Hibernate & Jackson = Could not write JSON: Infinite recursion

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:

  1. @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.

  2. @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 :)

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.

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