H M Sadman Haque
H M Sadman Haque

Reputation: 21

Jackson Serialization One to Many Relationships

@OneToMany(mappedBy = "departments")
@JsonManagedReference
private List<Employees> employeesList; 

@ManyToOne
@JoinColumn(name = "department_id")
@JsonBackReference
private Departments departments;

I have two Entities, Employees and Departments. Each Employee belongs to a Department. I used the @JsonManagedReference and @JsonBackReference to avoid infinite recursion.

But I cannot get Department of Employee from the Employee side as it gets ignored. In Laravel I could establish bidirectional relationships to get two way data.

What is the best way to implement and get bidirectional data when using Jackson for Spring? I want to know which department an employee is in from the employee side.

Upvotes: 0

Views: 3218

Answers (1)

BENMOHAMED Charfeddine
BENMOHAMED Charfeddine

Reputation: 161

First, let's annotate the relationship with @JsonManagedReference, @JsonBackReference ( reverse them in your exemple) to allow Jackson to better handle the relation:

public class Employees{
     @ManyToOne
     @JsonManagedReference
     private Departments departments;
}
public class Departments {
     @OneToMany(mappedBy = "departments")
     @JsonBackReference
     private List<Employees> employeesList; 
}

this solution can help you , if not yet you can use the annotation @JsonIdentityInfo that help with the serialization of entities with bidirectional relationship:

We add the class level annotation to our “Employees” entity:

@JsonIdentityInfo(
  generator = ObjectIdGenerators.PropertyGenerator.class, 
  property = "id")
public class Employees{ ... }

And to the “Departments ” entity:

@JsonIdentityInfo(
  generator = ObjectIdGenerators.PropertyGenerator.class, 
  property = "id")
public class Departments { ... }

Upvotes: 2

Related Questions