2012-11-22 29 views
0

我有三個表如何將一個表中的兒童保存在Hibernate中

客戶,關係,狀態

裏面我Client實體,我有

@ManyToOne(fetch = FetchType.EAGER) 
@JoinColumn(name = "relationId") 
private Relation relationId; 

@ManyToOne(fetch = FetchType.EAGER) 
@JoinColumn(name = "statusId") 
private Status statusId; 

關係和狀態實體只有getter/setter,沒有關係。

在這裏,我保存/更新我的客戶,以及與此我想保存/創建這個關係以及

Session session = sessionFactory.openSession(); 

try 
{ 

    Transaction tr = session.beginTransaction(); 
    updatedClient = (Client) session.get(Client.class, id); 
    updatedClient.setClientPostCode(client.getClientPostCode()); 
    updatedClient.setRelationId(client.getRelationId()); 

    session.saveOrUpdate(client.getRelationId()); 
    session.update(updatedClient); 
    tr.commit(); 
} 

有這段代碼也不例外,Client保存成功,成功創建Relation但創建的relationID未分配給客戶表中的relationID列。

其與該代碼創建的關係具有relationID(PrimaryKey的:3) 但在ClientrelationId柱,被保存的值始終爲0這實際上應該在這種情況下3

任何想法我做錯了什麼?

是不是有可能在 這一行之後得到relationId

session.saveOrUpdate(client.getRelationId()); 

所以,我可以得到relationId而不去DB和簡單地保存在標識我Client表?

+0

session.save(client.getRelationId()); \t \t \t session.flush();在這裏嘗試,但沒有運氣! – junaidp

+0

'commit'刷新會話並結束工作單元,如果flushmode未設置爲手動[FlushMode](http://docs.jboss.org/hibernate/orm/4.1/javadocs/org/hibernate/FlushMode。 html) – Peter

+0

是的,即使提交後,我沒有得到任何表生成的Id,因爲我在調試 – junaidp

回答

0

你可以嘗試在指定的@ManyToOne註釋的cascade參數:

@ManyToOne(fetch = FetchType.EAGER, cascade = CascadeType.ALL) 

它默認沒有級聯操作。

+0

@ManyToOne(fetch = FetchType.EAGER,cascade = CascadeType.ALL) \t @JoinColumn(name =「relationId」) \t private Relation relationId; :做到了這一點,但沒有運氣! – junaidp

相關問題