Search code examples
spring-bootspring-dataspring-data-jpajhipsterself-reference

Self-Referencing record leading to "Direct self-reference leading to cycle" exception


I have self referencing class

@Entity
@Table(name = "contacts")
@Cache(usage = CacheConcurrencyStrategy.NONSTRICT_READ_WRITE)
@Document(indexName = "contacts")
public class Contacts implements Serializable
{

private static final long serialVersionUID = 1L;

@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;

@Column(name = "username")
private String username;

@Column(name = "password_smartlpc")
private String password;

@Column(name = "full_name")
private String fullName;

@ManyToOne
private Contacts companyContact;
}

But for my one database record

id  full_name   username    password    company_contact_id  
5   JAK movies  abc          xyz               5

This record has company_contact_id as its self id.Which while retrieving goes into self-referencing cycle.

Enter: com.fps.web.rest.errors.ExceptionTranslator.processRuntimeException() 
with argument[s] = 
[org.springframework.http.converter.HttpMessageNotWritableException: Could not 
 write content: Direct self-reference leading to cycle (through reference 
 chain: java.util.UnmodifiableRandomAccessList[2]-
 >com.fps.domain.Contacts["companyContact"]-
 >com.fps.domain.Contacts["companyContact"]); nested exception is 
 com.fasterxml.jackson.databind.JsonMappingException: Direct self-reference 
 leading to cycle (through reference chain: 
 java.util.UnmodifiableRandomAccessList[2]-
  >com.fps.domain.Contacts["companyContact"]-
 >com.fps.domain.Contacts["companyContact"])]       

Work Around i have tried

(fetch = FetchType.LAZY) = gives same error as above.
@JsonIgnore :  removes error but does not retrieves Company_Contact_id
@JsonManagedReference @JsonBackReference same as above.

Unfortunately i cannot change database or alter it.Since its legacy.Any more things i can try ?? Thanks


Solution

  • Try using DTOs in JHipster, you'll get more control over JSON serialization rather than simply exposing your entity especially when you are constrained by legacy database schema.