Nested Query in Hibernate using Criterion

删除回忆录丶 提交于 2019-12-11 21:05:29

问题


I have a following query where I have to select rows from temporary table created by subquery.

select x, y, x 
from (select x, y, z from some_table where x between x1 and x2) 
where y like 'y1' 
order by z by desc

I have to use Criteria for fetching result from database

I have gone through several examples and documentation for handling subqueries using criteria and detached criteria. I have used Detached query but it is not serving the purpose or I am missing something.

I have used following code

    DetachedCriteria subCriteria =  
                      DetachedCriteria.forClass(SomeClass.class)
                     .add(Restrictions.between("x","x1","x2"))  
                     .setProjection(Projections.projectionList()
                     .add(Projections.property("x"))
                     .add(Projections.property("y"))
                     .add(Projections.property("z"));

   List<Object[]> results = session
                .createCriteria(Program.class)
                .add(Subqueries.exists(subCriteria))
                .add(Restrictions.like("y", "y1"))
                .addOrder(Order.desc("z")).list();

回答1:


Neither HQL or JPQL support "Derived Table Expressions". You can use sub-selects or in-selects but that's much it.

You need to use a native query this time and that's actually the right thing to do. HQL/JPQL are mostly useful when you want to fetch Entities not Projections.



来源:https://stackoverflow.com/questions/24796225/nested-query-in-hibernate-using-criterion

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!