【问题标题】:retrieving data from database as json in spring boot在spring boot中从数据库中检索数据作为json
【发布时间】:2016-07-09 10:42:16
【问题描述】:

我有一个 MySQL 数据库,我想以 json 格式检索一些数据。

我有一个实体Offre,它与AssociationCandidatOffre 实体有@OneToMany 关系。

我有一个在我的存储库中调用此方法的 api:

offreRepository.findAll();

Offre 实体:

@Entity
public class Offre implements Serializable {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "CODE_OFFRE")
    private Long codeOffre;
    private String titre;

    @OneToMany(mappedBy = "offre")
    private Collection<AssociationCandidatOffre> associationCandidatOffres;

    public Collection<AssociationCandidatOffre> getAssociationCandidatOffres() {
        return associationCandidatOffres;
    }

    public void setAssociationCandidatOffres(Collection<AssociationCandidatOffre> associationCandidatOffres) {
        this.associationCandidatOffres = associationCandidatOffres;


    }
     //... getters/setters      
    }

AssociationCandidatOffre 实体:

@Entity
public class AssociationCandidatOffre implements Serializable {
    @Id
    @GeneratedValue(strategy=GenerationType.IDENTITY)
    private Long idAssociation;
    private String lettreMotivation;
    private String tarifJournalier;
    private Date dateDisponibilite;

    @ManyToOne
    private Candidat candidat;

    @ManyToOne
    private Offre offre;
    @JsonIgnore
    @XmlTransient
    public Candidat getCandidat() {
        return candidat;
    }
    @JsonSetter
    public void setCandidat(Candidat candidat) {
        this.candidat = candidat;
    }
    @JsonIgnore
    @XmlTransient
    public Offre getOffre() {
        return offre;
    }
    @JsonSetter
    public void setOffre(Offre offre) {
        this.offre = offre;
    }

    //... getters/setters
}

问题是当我调用 api /offres 向我返回一个 json 对象时,我收到了以下错误消息:

    Failed to write HTTP message: org.springframework.http.converter.HttpMessageNotWritableException: Could not write content: could not extract ResultSet (through reference chain: java.util.ArrayList[0]->com.***.Rekrute.entities.Offre["associationCandidatOffres"]); 
nested exception is com.fasterxml.jackson.databind.JsonMappingException: could not extract ResultSet (through reference chain: java.util.ArrayList[0]->com.***.Rekrute.entities.Offre["associationCandidatOffres"])

当我在 getAssocationCandidatOffres 中使用 @JsonIgnore 时,我没有收到任何错误,但我也希望在 json 结果中具有该关联。

通常,这不应该产生任何错误,因为我在关系的另一边有 @JsonIgnore,即 getOffre()

我该如何解决这个问题?

【问题讨论】:

  • 您确定列表getAssocationCandidatOffres 已填充吗?请记住,当您展开列表时,处于调试模式的 IDE 通常会运行查询以在后台获取任何延迟加载列表。

标签: spring-boot jackson


【解决方案1】:

您无法将实体的双向关系转换为 JSON。 你得到一个无限循环。

JSON-Parser 从实体 Offer 开始,并通过 getAssociationCandidatOffres() 读取关联的 AssociationCandidatOffre。对于每个AssociationCandidatOffre,JSON 解析器读取getOffre() 并重新开始。解析器不知道什么时候必须结束。

【讨论】:

    猜你喜欢
    • 2015-07-24
    • 2020-08-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-09-10
    • 1970-01-01
    • 2017-01-15
    • 1970-01-01
    相关资源
    最近更新 更多