2015-06-22 105 views
0

在Hibernate中如何創建此查詢在Hibernate中創建查詢

"select test_type_nmbr from test_table where test_type_name in 
(select Test_type_name from test_table where test_type_nmbr in('111','222'))". 

這裏假設在數據庫中有價值觀類似如下:

test_type_nmbr | test_type_name 
------------------------------- 
111   | gre 
222   | gmat 
333   | gre 

現在你想獲得的所有test_type_ NMBR有「gre」作爲test_type_name(即'111'和'333'),你只有111個test_type_nmbr。

我需要使用2個不同的回調標準,或者我可以在1中進行嗎?如果1則請讓我知道如何。

+0

我不認爲需要的子查詢時是同桌 – Matt

+0

然後你可以建議如何在HQL寫? –

+0

爲什麼要使用兩個查詢來實現僅使用一個查詢就可以完成的操作? –

回答

0

嘗試此查詢

select a.test_type_nmbr from test_table a 
join test_table b on a.Test_type_name=b.Test_type_name 
where b.test_type_nmbr in('111','222') 
+1

你想要別的東西 –

0

嗯,我找到了答案,並使用分離標準已實施。在這裏,我使用分離標準來存儲我的子查詢,如果以後如果我想使用這個子查詢,我可以再次使用它的名稱。

讓這些數字出現在名爲testTypeList的列表中('111','222')。

final Criteria criteria = session.createCriteria(Test_Table.class,"testTable1"); 

    final DetachedCriteria detachedCriteria = DetachedCriteria.forClass(Test_Table.class, 
       "testTable2"); // testTable1 and testTable2 are aliases 
    detachedCriteria.add(Restrictions.in("testTable2.testTypeNmbr", testTypeList)); 
      final ProjectionList projectionList1 = Projections.projectionList(); 
      projectionList1.add(Projections.property("testTable2.testTypeName ")); 
    detachedCriteria.setProjection(projectionList1); 

    criteria.add(Property.forName("testTable1.testTypeName").in(detachedCriteria)); 
      final ProjectionList projectionList2 = Projections.projectionList(); 
      projectionList2.add(Projections.property("testTable1.testTypeName ")); 
    criteria.setProjection(projectionList2); 

return criteria.list(); // It will return all the test-numbers having test names that testTypeList contains.