2011-01-13 223 views
1

我想執行一個使用Hibernate標準api的子查詢,但沒能完全弄清楚如何去做。假設有兩張桌子,SHOPS和EMPLOYEES,其中SHOPS擁有所有商店信息,而EMPLOYEES是所有商店中所有僱員的大桌子(沒有外鍵)。我正在嘗試編寫一個查詢,它從SHOPS表中檢索商店ID和地址,然後通過連接檢索店鋪中的employess數量並計算在EMPLOYEES表中。事情是這樣的:休眠條件查詢

SELECT a.SHOP_ID, a.SHOP_ADDRESS, (SELECT COUNT(*) FROM 
SHOP_EMPLOYEES b WHERE b.SHOP_ID = a.SHOP_ID) as NUM_EMPLOYEES FROM <--Problem here 
SHOPS a 
WHERE 
QUERY_STATUS ='Open' 

所以我有一個Java類店與shopId,shopAddres,numEmployees和員工類似。

我的子查詢:

DetachedCriteria subquery = DetachedCriteria.forClass(
    Employee.class, "b").add(
    Property.forName("b.shopId").eqProperty("a.shopId")) 
    .setProjection(
    Projections.projectionList().add(
     Projections.rowCount())); 

而上的行主要條件查詢:

List shopListRet = session.createCriteria(Shop.class, "a") 
    .setProjection(
    Projections.projectionList().add(
     Projections.property("a.shopId"))).add(Subquery..."DONT KNOW WHAT SHOULD COME HERE").list(); 

我的問題是:

  • 如何將獨立查詢作爲關聯子查詢將計數結果收集到Shop類中的類變量numEmployees中?

感謝 -J

回答

2

使用SQL投影添加的子查詢。

String subSql = "SELECT COUNT(*) FROM SHOP_EMPLOYEES b WHERE b.SHOP_ID = a.SHOP_ID" 
... 
    .add(Projections.sqlProjection(
     subSql , 
     new String[] { "NUM_EMPLOYEES" }, 
     new Type[] { Hibernate.LONG } 
    ); 
+1

嗨感謝您的回覆。我不得不在查詢中調整一下以適應別名。像這樣:String subSql =「(SELECT COUNT(*)FROM SHOP_EMPLOYEES b WHERE b.SHOP_ID = {別名} .SHOP_ID)作爲NUM_EMPLOYEES」。之後工作。我接受你的答案是正確的 - 乾杯 - J – joesatch 2011-01-14 12:49:30