Help us understand the problem. What is going on with this article?

Play Framework 2.4 java ebean関連モデルのJson化

More than 3 years have passed since last update.

Play Framework 2.4で関連したモデルをJsonにするとこでハマったのでメモ

発生した問題

OneToManyのモデルをtoJson()したらthrough reference chainというエラー。
参照のループになってしまうみたい。

対応方法

Json.toJson()を使う場合は以下のアノテーションが必要。

項目等を無視させたい場合

サンプル(Userが複数のMemoを持ってるとする)

HogeController.java
    public Result test() {
        return ok(Json.toJson(User.find.byId(1L)));
    }
User.java
@Entity @Table(name = "users")
public class User extends Model {

    @Id
    public Long id;

    public String name;

    @OneToMany(cascade = CascadeType.ALL, mappedBy = "user")
    @JsonManagedReference
    public List<Memo> memos;

    public static final Find<Long, User> find = new Find<Long, User>(){};
}
Memo.java
@Entity @Table(name = "memos")
public class Memo extends Model {

    @Id
    public Long id;

    public String name;

    public String memo;

    @ManyToOne
    @JoinColumn(name = "user_id")
    @JsonBackReference
    public User user;
}
Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away