2015-06-22 63 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.