Question

I am getting a weird issue while using the hibernate Criteria for a inner query.

Below is the code snippet.

Criteria criteria = session.createCriteria(Restaurant.class);
criteria.addOrder(Order.asc("nid"));
DetachedCriteria innerIDs = DetachedCriteria.forClass(InnerTable.class).setProjection(Property.forName("tempId") );
criteria.add(Subqueries.in("id", innerIDs));
criteria.list()

This above code generated the SQL Script as:

1.    SELECT columns names
2.    FROM table name
3.    WHERE   ? IN (SELECT   this_.TEMP_ID AS y0_ FROM   global_temp_id this_)

In the line# 3, instead of getting the column name, I am getting ? (question mark). I tried even putting Property.forName("id") in Subqueries.in instead "id" still the same issue.

I have not mapped any relation to these 2 tables in hbm.xml files.

Was it helpful?

Solution

What you see is normal. Criteria queries are transformed to SQL queries executed using prepared statements. The id is a parameter of the statement.

If you want to select restaurants whose ID is in the subquery, then you need

criteria.add(Subqueries.propertyIn("id", innerIDs));

As the javadoc indicates, in() considers the first argument as a literal value:

Creates a criterion which checks that the value of a literal is IN the values in the subquery result.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top