[英]Hibernate Criteria Query for multiple columns with IN clause and a subselect
我從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()
criteria.add(Subqueries.propertiesIn(
new String[] { "field1", "field2" },
detachedCriteria));
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.