Reputation: 6251
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;}
}
Upvotes: 2
Views: 1230
Reputation: 116590
This is not an immediate solution, but Jackson 2.0.0 will finally have support for full Object Id handling, using @JsonIdentityInfo
annotation.
Documentation is still in-progress (page should be this); but unit tests have decent examples.
The idea will be to indicate types for which Object Id is needed (or, alternatively, indicate properties), and usage is very similar to that of @JsonTypeInfo
.
Jackson 2.0.0 RC1 was released a week ago, and the hope is that final 2.0.0 should go out before end of March 2012.
Upvotes: 2