Reputation: 1111
I want to show the "parent" data in the "child" entity response in a @manyToOne
relationship.
@Entity
public class Parent {
@JsonBackReference(value = "parent-children")
@OneToMany(mappedBy = "parent", targetEntity = Child.class)
private List<Children> children;
}
@Entity
public class Child {
@JsonManagedReference(value = "parent-children")
@ManyToOne
private Parent parent;
}
The response object for such a relationship is amazing, exactly what I want
GET web.site/children/all
[
{
"id": 1,
"parent": {
"id": 1,
"other": "data",
},
}
]
But when I run tests, the test runner can't compile! Searching for this error on Google gets me to several articles that say that I have the relationship the wrong way around.
com.fasterxml.jackson.databind.exc.InvalidDefinitionException: Cannot handle managed/back reference 'parent-children': back reference type (java.util.List) not compatible with managed type (website.entities.Child)
Switching the types around causes JSON results I don't want
GET web.site/children/all
[
{
"id": 1,
}
]
Upvotes: 0
Views: 275
Reputation: 1465
You could try using @JsonIgnoreProperties
like this:
@Entity
public class Parent {
@JsonIgnoreProperties("parent")
@OneToMany(mappedBy = "account", targetEntity = Child.class)
private List<Children> children;
}
@Entity
public class Child {
@JsonIgnoreProperties("children")
@ManyToOne
private Parent parent;
}
Some notes:
1) You are using mappedBy="account"
, why don't you use mappedBy="parent"
?
2) By convention, you should use private List<Children> childrens;
in plural
Upvotes: 1