使用spring Boot,在尝试将JPA对象转换为JSON时,我不断遇到以下错误:
nested exception is
`org.springframework.http.converter.HttpMessageNotWritableException:
Could not write JSON: Infinite recursion (StackOverflowError);
nested exception is com.fasterxml.jackson.databind.
JsonMappingException: Infinite recursion (StackOverflowError)
(through reference chain: interv.Entities.AppUser["projects"]->org.hibernate.collection.internal.PersistentBag[0]->interv.Entities.Project["appUser"]->interv.Entities.AppUser["projects"]->org.hibernate.collection.internal.Persis`
根据堆栈溢出中的一些解决方案,我在结束时添加了注释
@JsonIgnoreProperties,因此我的实体项目如下所示:
@Entity
@Data
@AllArgsConstructor
@NoArgsConstructor
public class Project implements Serializable{
@Id @GeneratedValue
private long id;
private String intitule;
private String description;
@OneToMany(mappedBy = "project" , fetch = FetchType.EAGER)
@Fetch(value = FetchMode.SUBSELECT)
@JsonIgnoreProperties("contrats")
private Collection<Contrat> contrats;
@ManyToOne
@JoinColumn(name = "Id_appUser")
@JsonIgnoreProperties("appUser")
private AppUser appUser;
}
api restful如下所示:
import java.util.List;
@RestController
public class ProjectsController {
@Autowired
private ProjectRepo projectRepo;
@RequestMapping(path = "/ListProjects", method = RequestMethod.GET)
public List<Project> getProjects(){
return projectRepo.findAll();
}
我尝试了其他注释,但始终出现相同的错误:
在弧延伸中,我得到:
200好的
分析JSON数据时出错
JSON输入意外结束
提前感谢您的帮助:)。
编辑:
文件AppUser。Java语言
@Entity
@Data
@AllArgsConstructor @NoArgsConstructor
public class AppUser implements Serializable {
@Id @GeneratedValue
private Long id;
@Column(unique = true)
private String username;
private String password;
@ManyToMany(fetch = FetchType.EAGER)
private Collection<AppRole> roles = new ArrayList<>();
@OneToMany(mappedBy = "appUser" , fetch = FetchType.EAGER)
@Fetch(value = FetchMode.SUBSELECT)
private Collection<Project> projects = new ArrayList<>();
@OneToMany(mappedBy = "appUser" , fetch = FetchType.EAGER)
@Fetch(value = FetchMode.SUBSELECT)
private Collection<Intervention> interventions = new ArrayList<>();
@OneToMany(mappedBy = "appUser" , fetch = FetchType.EAGER)
@Fetch(value = FetchMode.SUBSELECT)
private Collection<Contrat> contrats = new ArrayList<>();
}