2010-05-26 99 views
0

給定一個類Foo,Bar有hibernate映射到表Foo,A,B和CHibernate查詢匹配對象ID的對象列表

public class Foo { 
    Integer aid; 
    Integer bid; 
    Integer cid; 
    ...; 
} 

public class Bar { 
    A a; 
    B b; 
    C c; 
    ...; 
} 

我構建了一個任意大小的List fooList,我想用hibernate來獲取List裏面的結果列表將看起來像這樣:

Bar[1] = [X1,Y2,ZA,...] 
Bar[2] = [X1,Y2,ZB,...] 
Bar[3] = [X1,Y2,ZC,...] 
Bar[4] = [X1,Y3,ZD,...] 
Bar[5] = [X2,Y4,ZE,...] 
Bar[6] = [X2,Y4,ZF,...] 
Bar[7] = [X2,Y5,ZG,...] 
Bar[8] = ... 

其中每個Xi,Yi和Zi代表一個獨特的對象。

我知道我可以迭代fooList並獲取每個List並調用barList.addAll(...)來構建結果列表,如下所示:

List<bar> barList.addAll(s.createQuery("from Bar bar where bar.aid = :aid and ... ") 
    .setEntity("aid", foo.getAid()) 
    .setEntity("bid", foo.getBid()) 
    .setEntity("cid", foo.getCid()) 
    .list(); 
    ); 

有沒有更簡單的方法,理想情況下是一個更好地利用hibernate並進行最少量的數據庫調用?

我錯過了什麼嗎?休眠不適合這個嗎?

+0

FOO和BAR是否將FK和FH分開的表格都映射到映射A,B,C等的表格上? FOO和BAR之間的自然關係是什麼?將FK列映射爲整數而不是其映射對象的動機是什麼?這是一個非Hibernate的事情。 一個假設通過更好地使用休眠你的意思是,能夠通過一個對象關係訪問這個列表? – Affe 2010-05-26 16:42:50

+0

Foo是一個主表,Bar是一個細節表。 A,B,C都與主和細節都有FK關係。它們是之前項目正常化的結果。我可以將Ids切換爲正確的對象關係。 – sal 2010-05-26 19:38:18

回答

1

原來,以下做了什麼,我想:

  • 在需要選擇的項目
  • 映射應該鏈接複雜類型的屬性休眠 類映射酒吧定義組件的Foo通過一到一個映射的id
  • 填充富的列表,IDS將選擇酒吧

欄的列表的列表可以是對象通過

List<Foo> lf = this.getTheListOfFooWithIds(...); 
Query qb = session.createQuery("from Bar b where b.foo in (:foo)"); 
qb.setParameterList("foo", lf); 
List l = qb.list(); 

這讓我得到了我所需要的東西。

由hibernate創建的SQL並不像我期望的那麼糟糕。