Search code examples
hibernatejpaspring-data-jpanhibernate-mappingself-join

Self-join mapping entity using jpa and hibernate causes loop when executing findAll


I have an entity called investimento which needs to be self-joined since it has more investimento inside of it. I mapped it by following many guides here but when i execute a findAll with my service it just goes looping trying to execute itself over and over. What can i do to avoid this? The other @ManyToOne are just other tables with simple columns in them. How can i fix this please?

@Entity

@Table(name="investimento") public class Investimento implements Serializable {

private static final long serialVersionUID = 8883940320251385456L;

@Id
@GeneratedValue
@Column(name="id", nullable=false)
private Long id;

@Column(name="codice", nullable = false, unique = true)
private String codice;

@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name="codice_padre", referencedColumnName = "codice")
private Investimento investimentoPadre;

@OneToMany(mappedBy = "investimentoPadre",fetch = FetchType.LAZY)
private Set<Investimento> duplicati = new HashSet<Investimento>();

Solution

  • Finally fixed it, turns out i needed @JsonManagedReference because Jackson tries to serialise both ends of the relationship and ends up in a recursion.

    Found it also here : Infinite Recursion with Jackson JSON and Hibernate JPA issue