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

时间:2016-03-22 13:49:12

标签: spring-boot jackson

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

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

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

offreRepository.findAll();

Offre entity:

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

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

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

我该如何解决这个问题?

1 个答案:

答案 0 :(得分:2)

您无法将enitity的双向关系转换为JSON。 你得到了无限循环。

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