0

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();
3
  • Unless you post what you have tried, its hard to know what's not working for you, and by that I mean your Criteria, and DetachedCriteria statements Commented Jul 17, 2014 at 6:24
  • Does this have to be done with Hibernate? Looks like a perfect use-case for plain SQL to me. Also, why the derived table? In your example, there is not real need for nesting that query... Commented Jul 17, 2014 at 6:28
  • @Lukas ..I know that it can be used through plain SQL but I have to use Hibernate. Commented Jul 17, 2014 at 6:38

1 Answer 1

4

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.

Sign up to request clarification or add additional context in comments.

1 Comment

finally I chose native query.. Thanks

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.