2014-01-14 141 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