【发布时间】:2012-08-16 06:20:29
【问题描述】:
我正在使用 spring/hibernate 开发一个网站。我有一个域类“答案”,如下所示,
Answer.java
@Entity
public class Answer {
@OneToMany(fetch=FetchType.EAGER)
@JoinTable(name="Answer_comment",joinColumns=@JoinColumn(name="ANSWER_ID"),
inverseJoinColumns=@JoinColumn(name="COMMENT_ID"))
private Collection<Comment> comment;
-------------------------------------
-------------------------------------
}
所以我在 Answer 和 Comment 实体之间有一对多的关系。
为了测试这个我使用下面的代码,
Answer commentAnswer = answerService.getAnswer(1001);
Comment comment2 = new Comment();
comment2.setId(1004);
comment2.setBody("I cannot agree with your answer..because ...");
comment2.setUser(userService.getUser("ss"));
//commentService.create(comment2);
Comment comment3 = new Comment();
comment3.setId(1005);
comment3.setBody(" Yes I agree with your answer...sorry for my previous comment");
comment3.setUser(userService.getUser("ss"));
//commentService.create(comment3);
ArrayList<Comment> commentList = new ArrayList<Comment>();
commentList.add(comment2);
commentList.add(comment3);
commentAnswer.setComment(commentList);
answerService.editAnswer(commentAnswer);
我得到一个现有的答案 - 1001。并尝试将新创建的 2 个 cmets 添加到该答案的评论集合中。并保存该答案对象。
当我运行它时,我收到以下错误,
org.hibernate.LazyInitializationException: could not initialize proxy
- no Session at the line -- commentAnswer.setComment(commentList);
有人可以解释一下我在这里做错了什么吗?
谢谢
【问题讨论】:
-
这里有一个很好的答案:stackoverflow.com/questions/3041259/…
-
@chrislovecnm - 感谢您的链接.. 获得了一些知识