在spring boot中以json的形式从数据库中检索数据

Ich*_*aki 6 jackson spring-boot

我有一个MySQL数据库,我想以json的形式检索一些数据.

我有一个与实体Offre@OneToMany关系的AssociationCandidatOffre实体.

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

offreRepository.findAll();
Run Code Online (Sandbox Code Playgroud)

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      
    }
Run Code Online (Sandbox Code Playgroud)

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
}
Run Code Online (Sandbox Code Playgroud)

问题是,当我调用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"])
Run Code Online (Sandbox Code Playgroud)

当我@JsonIgnore在我使用时,getAssocationCandidatOffres我没有得到任何错误,但我也想在json结果中的那个关联.

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

我怎么解决这个问题 ?

小智 2

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

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