Summary:
Is there any way for Jackson to handle bidirectional references with polymorphic types where @JsonTypeInfo
is also used?
A note at the bottom of this page states no but it was written in 2010 and applied to Jackson v1.6.0 so I'm hoping maybe something has changed or someone can suggest an alternative approach.
Background:
I'm getting a JsonMappingException: Infinite recursion
error using the Jackson library and JPA. I know I can add @JsonIgnore
as suggested here but the downside is that I loose the bidirectional association when the JPA entities are serialized/deserialized.
Jackson v1.6.0 introduced the @JsonManagedReference
and @JsonBackReference
annotations. This looks great but the documentation from 2010 specifically states these annotations do not work with polymorphic handling using @JsonTypeInfo
, which of course is what I have.
Below is a contrived example of my entity classes:
@Entity
public class Owner implements Serializable {
@Id
@GeneratedValue
@Column(name="owner_id")
private Long id;
@OneToMany(mappedBy="pet", orphanRemoval=true, cascade=CascadeType.ALL)
private List<Pet> pets;
public List<Pet> getPets() {return pets;}
public void setPets(List<Pet> pets) {this.pets = pets;}
}
@Entity
@DiscriminatorColumn(name="pet_type")
@JsonTypeInfo(
use = JsonTypeInfo.Id.NAME,
include = JsonTypeInfo.As.PROPERTY,
property = "type")
@JsonSubTypes({
@Type(value = Dog.class, name = "dog"),
@Type(value = Cat.class, name = "cat"),
@Type(value = Bird.class, name = "bird") })
public class Pet implements Serializable {
@Id
@GeneratedValue
@Column(name="pet_id")
private Long id;
@ManyToOne
@JoinColumn(name="owner_id")
private Owner owner;
//@JsonIgnore
public Owner getOwner() {return owner;}
public void setOwner(Owner owner) {this.owner = owner;}
}