Hibernate Criteria Query用于IN子句和子查询的多列
我有一个和这个问题非常相似的问题。
我从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 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的相同查询:
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 = 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,我仍然很好奇。
尝试编写像这样的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()
Subqueries.propertiesIn是你需要的:
criteria.add(Subqueries.propertiesIn(
new String[] { "field1", "field2" },
detachedCriteria));
链接地址: http://www.djcxy.com/p/37121.html
上一篇: Hibernate Criteria Query for multiple columns with IN clause and a subselect
下一篇: Common criteria restriction in Hibernate for all queries for all tables