我有一个 MySQL 数据库,我想检索一些数据作为 json。
我有一个实体 Offre
有@OneToMany
与AssociationCandidatOffre
的关系实体。
我有一个 api,它在我的存储库中调用此方法:
offreRepository.findAll();
优惠实体:
@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()
.我怎么解决这个问题 ?
最佳答案
您无法将实体的双向关系转换为 JSON。
你得到一个无限循环。
JSON-Parser 从实体 Offer 开始并读取关联的 AssociationCandidatOffre
通过 getAssociationCandidatOffres()
.每 AssociationCandidatOffre
JSON 解析器读取 getOffre()
并重新开始。解析器不知道他什么时候必须结束。
关于spring-boot - 在spring boot中从数据库中检索数据作为json,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36156182/