I'm using Jackson to serialize my JPA model into JSON.
I have the following classes:
import com.fasterxml.jackson.annotation.*;
import javax.persistence.*;
import java.util.Set;
@JsonInclude(JsonInclude.Include.NON_NULL)
@JsonIgnoreProperties(ignoreUnknown = true)
@JsonIdentityInfo(generator = ObjectIdGenerators.PropertyGenerator.class)
@Entity
public class Parent {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String name;
@JsonManagedReference
@OneToMany(mappedBy = "parent", cascade = CascadeType.ALL, fetch = FetchType.EAGER)
private Set<Child> children;
//Getters and setters
}
and
import com.fasterxml.jackson.annotation.*;
import javax.persistence.*;
import java.util.HashSet;
import java.util.Set;
@JsonInclude(JsonInclude.Include.NON_NULL)
@JsonIgnoreProperties(ignoreUnknown = true)
@JsonIdentityInfo(generator = ObjectIdGenerators.IntSequenceGenerator.class)
@Entity
public class Child {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String name;
@JsonBackReference
@ManyToOne
@JoinColumn(name = "parentId")
private Parent parent;
//Getters and setters
}
I'm using the POJO mapping to serialize from model to JSON. When I serialize a Parent object I get the following JSON:
{
"id": 1,
"name": "John Doe",
"children": [
{
"id": 1,
"name": "child1"
},{
"id": 2,
"name": "child2"
}
]
}
But when I serialize a Child I get the following JSON:
{
"id": 1,
"name": "child1"
}
The reference to the parent is missing.
Is there a way to solve this?
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…