Kurt Bourbaki
Kurt Bourbaki

Reputation: 12616

Json and Jackson stackoverflow loop with unidirectional relationships

I know that since Jackson 1.6 I can use two annotations to solve the infinite recursion problem: @JsonManagedReference and @JsonBackReference.

The problem is that these annotations seem to work only in bi-directional relationships. My loop, instead, grows between 4 objects bounded with uni-directional associations. I paste the attributes that cause the stackoverflow loop with Json.

Cart:

@OneToMany(fetch=FetchType.LAZY,cascade=CascadeType.ALL,orphanRemoval=true)
@JoinColumn(name = "cart_fk")
private Collection<CartLine> cartLines = new ArrayList<CartLine>();

CartLine:

@OneToOne
@JoinColumn(name="product_fk")
private Product product;

Product:

@ManyToOne
private User user;

User:

@OneToMany(fetch=FetchType.LAZY,cascade=CascadeType.ALL,orphanRemoval=true)
@JoinColumn(name = "user_fk")
private Collection<Cart> cart = new ArrayList<Cart>();

So I've got this loop: Cart -> CartLine -> Product -> User -> Cart -> and so on.

How can I stop this loop, created by unidirectional relationships?

Upvotes: 0

Views: 862

Answers (1)

Sotirios Delimanolis
Sotirios Delimanolis

Reputation: 280141

You can annotate your Entity with

@JsonIdentityInfo(generator = ObjectIdGenerators.IntSequenceGenerator.class)

using whichever Generator you want. This will give an identifier to each object. If that object comes up again, Jackson will use its id instead of serializing it fully.

Upvotes: 2

Related Questions