程序问答   发布时间:2022-06-02  发布网站:大佬教程  code.js-code.com
大佬教程收集整理的这篇文章主要介绍了带有IN子句和子选择的多列的Hibernate Criteria Query大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。

如何解决带有IN子句和子选择的多列的Hibernate Criteria Query?

开发过程中遇到带有IN子句和子选择的多列的Hibernate Criteria Query的问题如何解决?下面主要结合日常开发的经验,给出你关于带有IN子句和子选择的多列的Hibernate Criteria Query的解决方法建议,希望对你解决带有IN子句和子选择的多列的Hibernate Criteria Query有所启发或帮助;

尝试像这样编写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()

解决方法

我从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标准。

大佬总结

以上是大佬教程为你收集整理的带有IN子句和子选择的多列的Hibernate Criteria Query全部内容,希望文章能够帮你解决带有IN子句和子选择的多列的Hibernate Criteria Query所遇到的程序开发问题。

如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。