2

当我在 Rich:dataTable 中加载延迟加载列表时,我总是收到“未能延迟初始化角色集合”错误。

这当然是因为会话在此状态下关闭。

我的问题如何仅使用 JPA(无弹簧等)来使用会话。我真的需要 HibernateUtil 的东西还是 Hibernate.Initialize(..)。我宁愿不使用这个 Hibernate 特定的东西,只是简单的 JPA。并且没有 EAGER 获取。

我当前的代码:

实体:

@SuppressWarnings("serial")
@Entity
@Table(name = "user", uniqueConstraints = {
    @UniqueConstraint(columnNames = "username"),
    @UniqueConstraint(columnNames = "email")})
public class User implements Serializable {

...

@OneToMany(mappedBy="user", fetch=FetchType.LAZY)
  private List<UserTournament> userTournament = new ArrayList<UserTournament>();

...

}

道:

@Stateless(name = "usercontroller")
public class UserController implements UserControllerInterface {

  @PersistenceContext
  private EntityManager em;

...

  @Override
  public List<UserTournament> getUserTournaments(Integer userid) {
    User user = loadUser(userid);
    return user.getUserTournament();
  }

...

}

命名豆:

@Named("myTournBean")
@ViewScoped
public class MyTournamentsBean implements Serializable {

  @EJB
  private UserControllerInterface userController;

  private List<UserTournament> tournaments;

...

  @PostConstruct
  public void init() {
...
    tournaments = userController.getUserTournaments(userid);
  }
...
}

xhtml:

<h:panelGrid columns="3" columnClasses="titleCell">

    <rich:dataScroller for="table" maxPages="5" />
        <rich:dataTable value="#{myTournBean.tournaments}" var="tourn"
                            id="table" rows="10">
            <rich:column>
            <f:facet name="header">
            <h:outputText value="Id" />
            </f:facet>
            <h:outputText value="#{tourn.id}" />
            </rich:column>
        </rich:dataTable>
    <rich:dataScroller for="table" maxPages="5" />
</h:panelGrid>

编辑:

@BoristheSpider的链接表格非常有帮助。我还没有完全通过它,但这已经解决了我的问题:

@Stateful
@ConversationScoped
public class Service
{
    @PersistenceContext(type = PersistenceContextType.EXTENDED)
    private EntityManager em;
}
4

1 回答 1

1

如果您不希望您的类依赖于 Hibernate,则创建一个实用程序类并依赖此实用程序类来初始化您的关联:

public class JPAUtils {
    public static void initialize(...) {
        Hibernate.initialize(...);
    }
}

并且当您更改您的 JPA 提供程序时(发生的可能性几乎为 0),然后使用新 JPA 提供程序的相应帮助程序类重写此方法,或者只需调用对象或集合的方法进行初始化。

于 2013-11-03T13:43:41.183 回答