2012-05-16 83 views
0

我有兩個名爲Expert和Technology的類,一個專家可以提供幾種技術,一個技術由幾位專家matrised。添加,更新技術獨立於專家級。從專家中刪除一個專業技術,只刪除相關的關係。如何使用hibernate標準來獲得正確的結果

Class Expert{ 
    Long id; // getter and setter 
    String name; // getter and setter; 
    Set<Technology> technos; // getter and setter 
} 

Technology{ 
    Long id; // gettter and setter 
    String name; //getter and setter 
} 

體現在Hibernate映射兩個類之間的關係是

<class name="Expert"> 
    <!-- put the declaration for id and name --> 

    <set name="technos" table="EXPERT_TECHNO" cascade="delete-orphan"> 
      <key column="id_expert"/> 
      <many-to-many column="id_techno" class = "Technology"/> 
    </set> 
</class> 

<class name="Technology"> 
<!-- put declaration for id and name--> 
</class> 

現在我有技術的情況下,我想找到誰MAITRISE所有的技術專家,因此如何使用Hibernate critera來獲得結果集?或者使用createQuery獲取結果集的最簡單方法。

我不熟悉冬眠critera方法,所以我呼籲你的幫助!

進一步的問題:

,當我想刪除從專家技術,我要的是簡單地刪除線表中的「EXPET_TECHNO」,howevery,我曾是expert.getTechnos.remove(TECHNO ),將從桌子上移除我不想擁有的技術!

回答

2

首先,解決這個問題最簡單的方法是將ManyToMany關聯設爲雙向。你只需要做

Set<Expert> experts = technology.getExperts(); 

現在,如果它不是一個選項,HQL會比標準這樣的查詢,這是不動態組成更加容易。查詢是那樣簡單

select expert from Expert expert 
inner join expert.technos techno 
where techno.id = :technoId 

如果你真的想和標準要做到這一點,那麼你需要做到以下幾點:

Criteria c = session.createCriteria(Expert.class, "expert"); 
c.createAlias("expert.technos", "techno"); 
c.add(Restrictions.eq("techno.id", technoId)); 

你可以自己找到這一點,並學到了很多其他的東西通過閱讀Hibernate documentation

+0

是的,我發現,createAlias函數是誤導性的。非常感謝您的支持。 – lhuang

+0

對於你的另一個問題,如何處理更新,刪除,使用多對多關聯的標準? – lhuang

+0

標準查詢只能從數據庫中進行選擇。要刪除或更新關聯,請從檢索專家的技術集合中刪除或更新實體。 –

相關問題