【问题标题】:org.hibernate.LazyInitializationException: could not initialize proxy - no Session exception while trying to add collectionorg.hibernate.LazyInitializationException:无法初始化代理 - 尝试添加集合时没有会话异常
【发布时间】: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);

有人可以解释一下我在这里做错了什么吗?

谢谢

【问题讨论】:

标签: spring hibernate


【解决方案1】:

嗯..我得到了这个工作。我正在使用 HibernateTemplate.load 方法来加载 Answer 实体。现在我将其更改为 HibernateTemplate.get 方法来加载 Answer 实体。它现在正在工作。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-07-29
    • 2011-12-01
    • 2014-04-21
    • 2019-05-10
    • 2015-11-09
    • 2021-08-10
    • 1970-01-01
    • 2013-10-22
    相关资源
    最近更新 更多