简体   繁体   中英

Nested Query in Hibernate using Criterion

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();

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM