2013-02-18 48 views
0

我有三個表,主表MAIN_TB與表TCHARS和TSTATUSES的外鍵,當我堅持MAIN_TB,重新查詢並顯示保存的記錄,連接的列(從TCHARS和來自TSTATUSES的t_status)爲空,但數據被保存。我可能會錯過什麼?實體管理器返回null爲加入列

表MAIN_TB

@JoinColumn(name = "T_STATUS", referencedColumnName = "T_STATUS") 
@ManyToOne 
private Tstatuses tStatus; 

@JoinColumn(name = "T_CHAR", referencedColumnName = "T_CHAR") 
@ManyToOne 
private Tchars tChar; 

表TCHARS

@OneToMany(mappedBy = "tChar") 
private Collection<MainTb> mainTbCollection; 

表TSTATUSES

@OneToMany(mappedBy = "tStatus") 
private Collection<MainTb> mainTbCollection; 

代碼

public void saveMainTb(){ 
    MainTb mainTb = new MainTb(); 
    Tchars tchars = new Tchars(); 
    Tstatuses tstatuses = new Tstatuses(); 

    tchars.setTChar(new Short("1")); 
    mainTb.setTChar(tchars); 

    tstatuses.setTStatus(new Short("1")); 
    mainTb.setTStatus(tstatuses); 

    mainTb.setTName("test"); 
    em.persist(mainTb); 

} 

結果

![Result][1] 

任何幫助,將理解

+0

分享查詢,您用來重新查詢您的持久對象。 – SudoRahul 2013-02-18 09:39:13

回答

0

,因爲沒有在任持有端或反向側指定級聯。我想你可以試試下面的代碼來手動保存所有實體實例:

em.persist(tchars); 
em.persist(tstatuses); 
mainTb.setTChar(tchars); 
mainTb.setTStatus(tstatuses); 
em.persist(mainTb); 
+0

改變了,但沒有運氣,'em.merge(tchars); em.merge(tstatuses); mainTb.setTChar(tchars); mainTb.setTStatus(tstatuses); em.merge(mainTb);'任何其他線索 – user2082589 2013-02-18 12:09:04

+0

我剛剛注意到,如果** MAIN_TB **表在部署應用程序時有數據,則會顯示字段,但如果表中的數據表爲空,則字段不會顯示不顯示,這裏是testApp的[link](https://www.dropbox.com/sh/ykejk8cjk3i1px3/nLf1vGD5Hd)。在Netbeans和Oracle XE數據庫上完成。 – user2082589 2013-02-18 12:24:16

0

您可以將下面的代碼添加到您的tStatusTCHAR

fetch=FetchType.EAGER 

如果您不需要總是獲取上述2個對象,那麼這會影響性能。

相反,你可以在查詢中添加fetch條款,獲取兩個子對象(tStatusTCHAR),與mainTb對象一起。這將爲您節省麻煩並獲取您在fetch子句中指定的所有子對象。性能優化器。

+0

將我的代碼更改爲@OneToMany(mappedBy =「tStatus」,fetch = FetchType.EAGER) private Collection mainTbCollection;和@OneToMany(mappedBy =「tChar」,fetch = FetchType.EAGER) private Collection mainTbCollection;仍然沒有運氣。 – user2082589 2013-02-18 11:59:36

+0

我的重新查詢代碼是findAll NamedQuery,即'@NamedQuery(name =「Tchars.findAll」,query =「SELECT t FROM Tchars t」)',然後我在我的邊界類(EJB無狀態)中調用它。 public List populateMyList(){ List mlist = em.createNamedQuery(「MainTb.findAll」)。getResultList(); return mlist; }然後將邊界類注入到我的託管bean(Session Scoped)中。 – user2082589 2013-02-18 12:07:05

+0

我剛剛注意到,如果** MAIN_TB **表在部署應用程序時有數據,則會顯示字段,但如果表中的數據庫爲空,則字段不顯示,這裏是[鏈接](https ://www.dropbox.com/sh/ykejk8cjk3i1px3/nLf1vGD5Hd)到testApp。在Netbeans和Oracle XE數據庫上完成。 – user2082589 2013-02-18 12:24:59