【问题标题】:Creating query in Hibernate在 Hibernate 中创建查询
【发布时间】:2015-06-22 09:46:44
【问题描述】:

在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 

现在您想要获取所有以“gre”作为 test_type_name(即“111”和“333”)的 test_type_nmbr,而您只有 111 个 test_type_nmbr。

我需要使用 2 种不同的回调标准还是可以使用 1 种?如果是 1,请告诉我如何操作。

【问题讨论】:

  • 同一张表我觉得不需要子查询
  • 那你能建议如何用hql写吗?
  • 为什么要使用两个查询来实现只用一个查询就可以完成的事情?
  • 你能用一个来写这个查询吗?我会尽力向你解释我想要什么。这里假设在数据库中你有如下值:
  • test_type_nmbr: test_type_name 111 gre 222 gmat 333 gre 现在您想要获取所有 test_type_ nmbr 的 test_type_name 为“gre”(即“111”和“333”),而您只有 111 个 test_type_ nmbr和你一起。

标签: sql hibernate hql detachedcriteria


【解决方案1】:

试试这个查询

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' )

【讨论】:

  • 操作者想要别的东西
【解决方案2】:

好吧,我找到了答案,并使用分离的标准实现了它。在这里,我使用分离的条件来存储我的子查询,如果以后我想使用这个子查询,我可以使用它的名称再次使用它。

让这些数字出现在一个名为 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.

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-01-08
    • 2016-08-29
    • 1970-01-01
    • 2012-02-19
    • 1970-01-01
    • 2015-08-30
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多