私が構築しようとしているプロジェクトでは、ユーザー クラスからクラス ユーザーへの manyToMany 関係が必要です (ユーザーには友達がいて、友達はユーザーの友達です)。JPA で Json を SpringBoot から抜け出そうとするとき。JSON で再帰ループが発生します (これは、2 人のユーザーがお互いの友人である場合にのみ発生します)。
何が起こるかはわかっていますが、問題の解決策が見つかりません。ご覧のとおり、ビューを「フィルタリング」するためにさまざまなビューを使用しています。問題は次のとおりです。どうすれば再帰を停止できますか?
@Entity
public class User {
@Id
@GeneratedValue
@JsonView(JsonViews.UserView.class)
private long userId;
@JsonView(JsonViews.UserView.class)
private String username;
@JsonView(JsonViews.UserView.class)
private String password;
@JsonView(JsonViews.UserView.class)
private String email;
@JsonView(JsonViews.UserView.class)
private String location;
//private String avatar;
@JsonView(JsonViews.UserView.class)
private int ranking;
private String UserStatus;
//Friend Relation Many > Many
@JsonView({JsonViews.UserView.class, JsonViews.FriendWith.class})
@ManyToMany()
private List<User> friendsWith;
@ManyToMany(mappedBy = "friendsWith")
private List<User> friendOf;
@JsonView({JsonViews.UserView.class, JsonViews.Player.class})
@OneToMany(mappedBy = "user")
private List<Player> player;
public User() {
this.friendsWith = new ArrayList<>();
this.friendOf = new ArrayList<>();
}
public User(String username, String password, String email, String location, int ranking) {
this();
//this.userId = userId;
this.username = username;
this.password = password;
this.email = email;
this.location = location;
this.ranking = ranking;
}
// and th usual getters and setters
スタック:
2019-12-10 22:17:52.414 ERROR 1618 --- [nio-8084-exec-1] o.a.c.c.C.[.[.[/].[dispatcherServlet] : Servlet.service()
for servlet [dispatcherServlet] in context with path [] threw exception [Request processing failed; 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: org.hibernate.collection.internal.PersistentBag[0]->
nl.hva.ewa.stratego.backend.models.User["friendsWith"]->
org.hibernate.collection.internal.PersistentBag[0]->
nl.hva.ewa.stratego.backend.models.User["friendsWith"]->
org.hibernate.collection.internal.PersistentBag[0]->
nl.hva.ewa.stratego.backend.models.User["friendsWith"]->
org.hibernate.collection.internal.PersistentBag[0]->
nl.hva.ewa.stratego.backend.models.User["friendsWith"]->
ETC.... ETC.....
完全を期すために、JsonViews クラス:
public class JsonViews {
public class UserView { };
public class AComplete extends UserView { };
public class BComplete extends UserView { };
public class FriendsWith extends UserView {};
public class FriendsOf extends UserView {};
public class Player extends UserView {};
}