小编典典

带有IN子句和子选择的多列的Hibernate Criteria Query

hibernate

我从table1中选择所有数据,以匹配table2中field3和field4的所有匹配唯一组合。

这是我精简的SQL:

select *
from table1 as t1
where (t1.field1, t1.field2) in (select distinct field3, field4
                                 from table2 as t2
                                 where t2.id=12345);

我需要将我的SQL转换为hibernate条件。我的实体对象正确映射到了表,并将响应转换为正确的结果实体,但是我无法正确转换where子句。

我有的

Criteria criteria = getSession().createCriteria(Table1.class);

DetachedCriteria subquery = DetachedCriteria.forClass(Table2.class);
ProjectionList projectionList = Projections.projectionList();
projectionList.add(Projections.property("field3"), "field3");
projectionList.add(Projections.property("field4"), "field4");
subquery.setProjection(Projections.distinct(projectionList));
subquery.add(Restrictions.eq("id", 12345));

我希望我的where子句类似于:

criteria.add(Subqueries.in("field1, field2", subquery));

但这是hibernate所不允许的。

我尝试推出where子句以具有两个子查询,并对照结果检查field1和field2,但似乎子查询将始终必须返回多个列。我使用分组依据进行了此操作,但是Hibernate会自动将分组依据中的列添加到投影列表中,但我找不到删除它们的方法。

这是使用group by的相同查询:

select *
from table1 as t1
where t1.field1 in (select field3
                    from table2 as t2
                    where t2.id=12345
                    group by field3, field4)
  and t1.field2 in (select field4
                    from table2 as t2
                    where t2.id=12345
                    group by field3, field4);

是否可以使用hibernate条件来执行我的where子句?

如果无法使用Hibernate Criteria,是否可以使用HQL执行where子句?

编辑:

@ Larry.Z使用HQL回答了我的问题。

我可以使用“hibernate标准”解决问题,但必须将查询修改为:

select *
from table1 as t1
where exists (select 1
              table2 as t2
              where t2.id=12345
                and t2.field3=t1.field1
                and t2.field4=t1.field2);

转换为hibernate标准:

Criteria criteria = getSession().createCriteria(Table1.class, "t1");

DetachedCriteria subquery = DetachedCriteria.forClass(Table2.class, "t2");
subquery.add(Restrictions.eq("t2.id", 12345));
subquery.add(Restrictions.eqProperty("t2.field3", "t1.field1"));
subquery.add(Restrictions.eqProperty("t2.field4", "t1.field2"));
subquery.setProjection(Projections.property("t2.id")); // select the ID rather than 1

我仍然好奇是否有可能使用我的原始SQL编写hibernate标准。


阅读 260

收藏
2020-06-20

共1个答案

小编典典

尝试像这样编写HQL查询

String hql = "from Table1 t1 where (t1.field1, t1.field2) in (
    select distinct t2.field3, t2.field4
    from Table2 t2
    where t2.id=12345)";
sessionFactory.getCurrentSession().createQuery(hql).list()
2020-06-20