-
Notifications
You must be signed in to change notification settings - Fork 109
Description
I have a stackoverflow problem, but it occurs only depending on the entity that initialize first.
@Entity @Table(name="contrato")
public class Contrato {
@Id
private Long id;
private String numeroContrato;
@OneToMany(mappedBy="contrato") @JsonIgnoreProperties("contrato")
private List<Parcela> parcelas;
@OneToMany(mappedBy="contrato") @JsonIgnoreProperties("contrato")
private List<Liquidacao> liquidacoes;
}
@Entity @Table(name="contrato_parcela")
public class Parcela {
@Id
private Long id;
private Integer numeroParcela;
@ManyToOne(fetch=FetchType.LAZY) @JoinColumn(name="contrato_id")
private Contrato contrato;
}
@Entity @Table(name="contrato_liquidacao")
public class Liquidacao {
@Id
private Long id;
private BigDecimal valorTotal;
@ManyToOne(fetch=FetchType.LAZY) @JoinColumn(name="contrato_id")
private Contrato contrato;
@ManyToOne(fetch=FetchType.LAZY) @JoinColumn(name="contrato_parcela_id") @JsonIgnoreProperties("contrato")
private Parcela parcela;
}
This block below works perfectly with the expected return: {"numeroContrato":"101-6861944","parcelas":[{"numeroParcela":3}],"liquidacoes":[{"valorTotal":91548.00,"parcela":{"numeroParcela":3}}]}
final Contrato contrato = em.find(Contrato.class, 1L);
Hibernate.initialize(contrato.getParcelas());
Hibernate.initialize(contrato.getLiquidacoes());
mapper.writer().writeValueAsString(contrato);
But that other code block, where I changed the boot order of the relationship I have a stackoverflow.
Contrato contrato = em.find(Contrato.class, 1L);
Hibernate.initialize(contrato.getLiquidacoes());
Hibernate.initialize(contrato.getParcelas());
mapper.writer().writeValueAsString(contrato);
Exception in thread "main" com.fasterxml.jackson.databind.JsonMappingException: Infinite recursion (StackOverflowError) (through reference chain: teste.jackson.Contrato["parcelas"]->org.hibernate.collection.internal.PersistentBag[0]->teste.jackson.Parcela["contrato"]->teste.jackson.Contrato["parcelas"]->org.hibernate.collection.internal.PersistentBag[0]->teste.jackson.Parcela["contrato"]->teste.jackson.Contrato["parcelas"]->org.hibernate.collection.internal.PersistentBag[0]->teste.jackson.Parcela["contrato"]->teste.jackson.Contrato["parcelas"]->org.hibernate.collection.internal.PersistentBag[0] ...