简体   繁体   中英

Hibernate query with subquery in WHERE clause and multiple joins

I have been trying to get Hibernate to generate me a query with a subquery in its where clause. I've used this answer as a base to help me going , but this question mentioned only one table.

However, this is what I would need (in SQL):

SELECT [...]
FROM a
LEFT OUTER JOIN b on a.idb = b.idb
LEFT OUTER JOIN c on b.idc = c.idc
[...]
LEFT OUTER JOIN k out on j.idk = k.idk
WHERE k.date = (SELECT max(date) from k in where in.idk = out.idk) OR k.date is null 

As I am not very used to using Hibernate, I'm having trouble specifying these inner joins while navigating in the inner constraints. I was able to re-create the initial criteria as in the linked answer, but I can't seem to join the criteria and the rootCriteria.

If the entities are properly joined with @ManyToOne annotations, simply joining the criteria to the previous table will be enough to propagate the criteria to the whole query.

The following code seems to work properly to add the WHERE clause I'm looking for.

DetachedCriteria kSubquery = DetachedCriteria.forClass(TableJPE.class,"j2");
kSubQuery = kSubQuery.createAlias("k","k2");
kSubQuery.setProjection(Projections.max("k2.date"));
kSubQuery = kSubQuery.add(Restrictions.eqProperty("j.id", "j2.id"));
rootCriteria.add(Restrictions.disjunction()
     .add(Subqueries.propertyEq("k.date",kSubQuery))
     .add(Restrictions.isNull("k.date")));

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