我一直在尝试在两个实体(团队和竞赛)之间创建@ManyToMany关系,但是当我尝试发布到竞赛控制器API时,我得到了一个错误415
Failed to evaluate Jackson deserialization for type [[simple type, class com.project.Contest.Contest]]: com.fasterxml.jackson.databind.exc.InvalidDefinitionException: Cannot handle managed/back reference 'defaultReference': back reference type (`java.util.List<com.project.Contest.Contest>`) not compatible with managed type (com.project.Contest.Contest)
团队:
@Getter
@Setter
@NoArgsConstructor
@AllArgsConstructor
@Entity
@Table(name = "team")
public class Team {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private long id;
@JsonBackReference
//@JsonIdentityInfo(generator = ObjectIdGenerators.PropertyGenerator.class , property = "id")
@ManyToMany(mappedBy = "teams", cascade = CascadeType.PERSIST)
private List<Contest> contests;
private String name;
private int wins, losses;
}
竞赛:
@Getter
@Setter
@NoArgsConstructor
@AllArgsConstructor
@Entity
@Table(name = "contest")
public class Contest {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private long id;
private String name;
@ManyToMany(cascade = CascadeType.PERSIST)
@JsonManagedReference
//@JsonIdentityInfo(generator = ObjectIdGenerators.PropertyGenerator.class , property = "id")
@JoinTable(
name = "team_contest",
inverseJoinColumns = @JoinColumn(name = "team_id"),
joinColumns = @JoinColumn( name = "contest_id")
)
private List<Team> teams;
@ManyToMany(cascade = CascadeType.PERSIST)
@JsonManagedReference
//@JsonIdentityInfo(generator = ObjectIdGenerators.PropertyGenerator.class , property = "id")
@JoinTable(
name = "contest_user",
joinColumns = @JoinColumn(name = "contest_id"),
inverseJoinColumns = @JoinColumn( name = "user_id")
)
private List<User> users;
}
我发现我可以使用@JsonIdentityInfo(生成器=对象标识生成器.属性生成器.类,property ="id")而不是@JsonBackReference和@JsonManagedReference,这对我很有帮助,因为它让我可以发布到数据库,但随后我又遇到了无法检索比赛的问题。因为两个对象都有对彼此的引用,所以它创建了某种无限循环以到达第二个对象的引用(contest. teams [1])它需要显示contest. teams [0]对contest和soo forth的引用。请帮助〈3
2条答案
按热度按时间k4ymrczo1#
这是最著名的双向问题。要在序列化时中断循环,可以选择:
1.@JSON忽略
1.@JSON身份信息
1.@EntityGraph或简单地使关系单向
dhxwm5r42#
感谢meridbt我已经在使用@JsonIdentityInfo,但在错误的地方,我读了一些在线和修复我的问题,这样做:
团队:
竞赛: