【问题标题】:Self-Referencing record leading to "Direct self-reference leading to cycle" exception自引用记录导致“直接自引用导致循环”异常
【发布时间】:2018-04-10 05:10:57
【问题描述】:

我有自引用类

@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;
}

但是对于我的一个数据库记录

id  full_name   username    password    company_contact_id  
5   JAK movies  abc          xyz               5

此记录以 company_contact_id 作为其自身 id。检索时进入自引用循环。

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"])]       

我尝试过的解决方法

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

不幸的是,我无法更改数据库或更改它。因为它是遗留的。我可以尝试更多的东西吗?? 谢谢

【问题讨论】:

    标签: spring-boot spring-data spring-data-jpa jhipster self-reference


    【解决方案1】:

    在 JHipster 中尝试using DTOs,您将获得对 JSON 序列化的更多控制,而不是简单地公开您的实体,尤其是当您受到旧数据库架构的限制时。

    【讨论】:

    • 谢谢你,先生,这帮助了很多:)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-01-24
    • 1970-01-01
    • 2018-11-27
    • 2021-08-28
    • 2017-07-27
    • 1970-01-01
    相关资源
    最近更新 更多