2013-11-03 27 views
2

當我在rich:dataTable中加載惰性加載列表時,我總是得到「無法懶惰地初始化角色集合」錯誤。與JPA的會話

這當然是因爲會話在此狀態下關閉。

我的問題我怎樣才能使用會話通過使用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>(); 

... 

} 

DAO:

@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(); 
    } 

... 

} 

的bean:

@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> 

編輯:

link形式@BoristheSpider是非常有益的。我不能完全通過,但這個已經解決了我的問題:

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

如果您不想保持會話打開,您將不得不加載數據。如果你不想急於獲取你是不幸的... –

+0

在這裏,我們去:http://stackoverflow.com/questions/12770450/standard-jpa-method-to-initialize-lazy-entity –

+0

但是沒有辦法讓會話與JPA保持一致?我對這個JPA主題頗爲陌生。到目前爲止,我一度使用HibernateUtil方法。但我寧願避免它,只是使用JPA與persictence.xml並沒有額外的hibernate.cfg.xml。 – Dave

回答

0

如果你不想讓你的類依賴於休眠,然後創建一個實用工具類,並依靠這個工具類初始化協會:

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

當你改變你的JPA提供者(其幾乎爲0的機率發生),然後重寫使用相應的輔助類新的JPA提供者的這種方法,或通過簡單地調用或對象的方法收集進行初始化。