我正在使用spring / hibernate开发一个网站。我有一个域类'答案',如下所示,
@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 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条评论。并保存该答案对象。
当我运行时,我收到以下错误,
org.hibernate.LazyInitializationException: could not initialize proxy
- no Session at the line -- commentAnswer.setComment(commentList);
有人可以解释我在这里做错了什么吗?
由于
答案 0 :(得分:3)
嗯..我得到了这个工作。我正在使用HibernateTemplate.load方法来加载Answer实体。现在我将其更改为HibernateTemplate.get方法以加载Answer实体。它现在正在运作。