我有一个问题,与这个问题非常相似。
我正在从table2中选择field3和field4的所有匹配唯一组合,以获取table1中的所有数据。
以下是我简化后的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 Criteria。我的实体对象正确映射到表格,并将响应转换为正确的结果实体,但我无法正确翻译我的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,但似乎子查询始终必须返回多列。我使用 group by 进行了尝试,但是 Hibernate 会自动将 group by 中的列添加到 projection 列表中,无法找到删除它们的方法。
这是使用 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 Criteria来编写我的where子句?
如果不可能使用Hibernate Criteria,是否可以使用HQL来编写我的where子句?
编辑:
@Larry.Z使用HQL回答了我的问题。
我能够使用Hibernate Criteria解决我的问题,但是我必须修改查询为:
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 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 Criteria。