2017-04-18 14 views
1

ソーシャルメディアサイトで実行できるように、1人のユーザーが別のユーザーを「フォロー」できるEclipseLinkプロジェクトに取り組んでいます。私はUserエンティティ(usersというテーブルを参照しています)に「フォロワー」(そのユーザーに続くユーザー)と「フォロー」(ユーザーがフォローしているユーザー)のリストを持つ設定をしています。この関係は、従属ユーザーID(user_id)と次のユーザーID(follower_id)の列を含む別のテーブルfollowersに定義されています。JPAの多対多関係が無限再帰とスタックオーバーフローエラーを引き起こします

私のユーザモデルは次のようになります。

@Entity 
@Table(name = "users") 
@NamedQuery(name = "User.findAll", query = "SELECT u FROM USER u") 
public class User { 
    // other attributes 
    @ManyToMany(fetch = FetchType.LAZY) 
    @JoinTable(name = "follower", joinColumns = @JoinColumn(
     name = "user_id", referencedColumnName = "id"), 
    inverseJoinColumns = @JoinColumn(
     name = "follower_id", referencedColumnName = "id")) 
    private List<User> followers; 

    @ManyToMany(mappedBy = "followers") 
    private List<User> following; 

    // other getters and setters 
    public List<User> getFollowers() { 
     return this.followers; 
    } 

    public List<User> getFollowing() { 
     return this.following; 
    } 
} 

getFollowers()方法が正常に動作するようだが、getFollowing()が呼び出されたときに、私はStackOverflowExceptionがで絶頂に達するコンソールスパムの束を得る:

com.fasterxml.jackson.databind.JsonMappingException: Infinite recursion 
(StackOverflowError) (through reference chain: 
org.eclipse.persistence.indirection.IndirectList[0]- 
>org.myproject.model.User["followers"]- 
>org.eclipse.persistence.indirection.IndirectList[0]- 
>org.myproject.model.User["following"]- 
... 
at com.fasterxml.jackson.databind.ser.std.BeanSerializerBase 
.serializeFields(BeanSerializerBase.java:518) 
at com.fasterxml.jackson.databind.ser.BeanSerializer.serialize 
(BeanSerializer.java:117) 
at com.fasterxml.jackson.databind.ser.impl.IndexedListSerializer 
.serializeContents(IndexedListSerializer.java:94) 
at com.fasterxml.jackson.databind.ser.impl.IndexedListSerializer 
.serializeContents(IndexedListSerializer.java:21) 
... 

さらにスタックトレースを提供する必要があるかどうか教えてください。何かヒント?

+2

@JacksonIgnoreは確かにそれは(あなたがJsonIgnore' @ '意味と仮定して)なかった問題 – ketrox

+0

を解決する必要があります確認してください。あなたは命の恩人です! – Ecliptica

+0

情報を失うことなく逆シリアル化できますか? – efekctive

答えて

2

@OneToMany(コレクション)を使用するたびに、@JsonIgnoreを追加する必要があります。そうしないと、親(片側)と参照側の間で参照を維持するため、スタックオーバーフロー例外が発生する無限ループが発生します。この種の問題に対処する詳細については、子(多くの側) は、あなたのコレクションのために、この素​​晴らしい記事http://www.baeldung.com/jackson-bidirectional-relationships-and-infinite-recursion

+0

私のために働いた、ありがとう! – Ecliptica