我有这个奇怪的问题,任何对所述数据结构的调用在实例化为Stack时都会产生nullPointerException,但在实例化为List时则不会。
当我使用堆栈类运行它时,单元测试和运行play web服务器都会给出nullPointerException
这有效:
....
/*
* comment belongs to post, and if post is deleted,
* the deletion is relayed to all comments that post object
* owns
*/
@OneToMany (mappedBy="post",cascade=CascadeType.ALL)
public List<Comment> comments;
....
public Post(SuperUser author,String content,String title){
this.comments = new LinkedList<Comment>();
this.author = author;
this.content = content;
this.title = title;
this.postedAt = new Date();
}
...
public Post addComment(Comment newComment){
this.comments.add(newComment);
this.save();
return this;
}
这不起作用:
....
/*
* comment belongs to post, and if post is deleted,
* the deletion is relayed to all comments that post object
* owns
*/
@OneToMany (mappedBy="post",cascade=CascadeType.ALL)
public Stack<Comment> comments;
....
public Post(SuperUser author,String content,String title){
this.comments = new Stack<Comment>();
this.author = author;
this.content = content;
this.title = title;
this.postedAt = new Date();
}
...
public Post addComment(Comment newComment){
this.comments.push(newComment); // ERROR
this.save();
return this;
}
我尝试为List接口编写一个包装器接口,并为其提供方法:
public E push(E elem);
但这也行不通。
知道这可能是什么吗?
答案 0 :(得分:1)
您不能使用具体类作为实体关联的类型。只有接口:List,Set,Map。 ORM使用它们自己的这些接口的具体实现来实现脏检查,延迟加载等。
规范的相关引用:
必须根据以下某个集合值接口定义集合值持久字段和属性,而不管实体类是否遵守上述JavaBeans方法约定以及是否使用字段或属性访问:java。 util.Collection,java.util.Set,java.util.List,java.util.Map。应用程序可以使用集合实现类型在实体持久化之前初始化字段或属性。一旦实体被管理(或分离),后续访问必须通过接口类型。