JSF和JPA与@ManyToMany和自定义转换器:LazyInitializationException

时间:2012-10-27 18:15:39

标签: java jpa jsf-2 many-to-many

我有一个@Entity

@Entity
public class Issue implements Serializable
{
  @Id @GeneratedValue(strategy=GenerationType.IDENTITY)
 protected long id; 

 @ManyToOne
 private IssueScope scope;

  //getter/setter
}

我使用自定义IssueScopeConverter直接将IssueScope f:selectItems 一起使用。转换器只是

  • 返回方法getAsString
  • id
  • IssueScope
  • 返回新创建的对象getAsObject id 设置)

使用 p:selectOneMenu 以及代码如下的类似组件,这不会引起任何问题(以及@ManyToOne之前多次使用过):

<h:form id="fScope">
  <p:selectOneButton rendered="true" value="#{issueBean.issue.scope}"
                     converter="IssueScopeConverter">  
    <f:selectItems value="#{issueBean.issueScopes}" var="s"
                   itemLabel="#{s.name}" itemValue="#{s}"/>
  </p:selectOneButton>
  <p:commandButton value="Save" actionListener="#{issueBean.save()}"/>
</h:form>

现在让我们描述一下我的问题:事实上我不需要@ManyToOne,我需要@ManyToManyIssue的{​​{1}}关系:

IssueScope

并且XHTML将更改为:

@ManyToMany(fetch=FetchType.EAGER)
private List<IssueScope> scopes;

如果我新创建<h:form id="fScopes"> <p:selectManyCheckbox value="#{issueBean.issue.scopes}" converter="ErpIssueScopeConverter"> <f:selectItems value="#{issueBean.issueScopes}" var="s" itemLabel="#{s.name}" itemValue="#{s}"/> </p:selectManyCheckbox> <p:commandButton value="Save" actionListener="#{issueBean.save()}"/> </h:form> ,然后按保存按钮来保留实体,则无异常完成。即使选定的Issue也会被保留。然后,如果我想更新实体,按下按钮后会得到IssueScopes

我的failed to lazily initialize a collection, no session or session was closed: org.hibernate.LazyInitializationException: failed to lazily initialize a collection, no session or session was closed中的public void save()方法永远不会输入。

问题似乎与Lazy loading exception when using JSF Converter (refering to a collection)有关,但我没有使用Seam持久性或者有特殊的TransactionInterceptor`。

1 个答案:

答案 0 :(得分:1)