java eq in_Hibernate Criteria使用IN子句和子选择查询多个列

我有一个非常类似于this question的问题 .

我从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子句 .

What I Have

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子句?

EDIT:

@ 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,我仍然很好奇 .

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值