2014-01-14 127 views
0

在Play Framework 2.0的Java版本中,Im試圖在我的另一個類ForumThread中保存一個名爲Post的類的ArrayList。現在,在ForumThread的構造函數中,我創建了一個新的Post並將其添加到帖子的ArrayList中,然後保存我的數據庫。但是,在保存ForumThread的任何實例後,Post的ArrayList變爲空。當我渲染我的頁面時,這會導致錯誤,這裏我的問題是雙重的。Play Framework 2.0 Ebean ArrayList Null

1)如何讓我的ForumThread的帖子ArrayList一旦保存就不會變爲空?

2)爲什麼一旦它被保存就會變爲空。

所有相關代碼都在下面,並且作爲說明,我嘗試了使用@ManyToOne和@OneToMany註釋,但沒有成功,這是在嘗試執行代碼之前的代碼。

ForumThread.java

package models; 

import java.util.*; 
import controllers.*; 
import play.db.ebean.*; 
import play.data.validation.Constraints.*; 

import javax.persistence.*; 

@Entity 
@Table(name="threads") 
public class ForumThread extends Model{ 

    @Id 
    public long id; 

    @Column 
    @Required 
    public String title; 

    @Column 
    public User creator; 

    @Column 
    public List<Post> posts = new ArrayList<Post>(); 

    public String initialMessage; 

    public static play.db.ebean.Model.Finder<Long, ForumThread> find = new Finder<Long, ForumThread>(Long.class, ForumThread.class); 

    public ForumThread(User creator, String title, String initialMessage) { 
     this.creator = creator; 
     this.title = title; 
     Post initialPost = new Post(creator, initialMessage, title); 
     this.posts.add(initialPost); 
    } 

    public static void create(ForumThread thread){ 
     thread.save(); 
    } 

    public static List<ForumThread> all(){ 
     return find.all(); 
    } 
} 

Post.java

package models; 

import java.util.*; 

public class Post{ 
    public User poster; 
    public String message; 
    public String title; 

    public Post(User poster, String message, String title){ 
     this.poster = poster; 
     this.message = message; 
     this.title = title; 
    } 
} 

回答

0

看起來像你的Posts類只是一個POJO。應該延伸Model,並且還應該有一個@Entity,@Table等註釋。

0

要確保一切都被正確地推斷,實施ForumThread和郵政之間的雙向關係,表示職位映射到一個線程的屬性和使用級聯保存:

@Entity 
public class ForumThread extends Model{ 
    ... 
    @OneToMany(mappedBy="thread",cascade=CascadeType.ALL) 
    public List<Post> posts; 
    ... 
} 


@Entity 
public class Post extends Model{ 
    ... 
    @ManyToOne 
    public ForumThread thread; 
    ... 
} 

看到ebean userguide http://www.avaje.org/doc/ebean-userguide.pdf