简体   繁体   中英

Add criteria to subselect?

With Hibernate Criteria based queries, can you add criteria to a subselect at all?

Specifically a developer has the following code;

 criteria.setFetchMode("user", FetchMode.JOIN).add(
                Restrictions.eq("company.id", companyId));

Their intention is something like;

select a.* from tableA a where a.user in 
        (select b.user from tableB b where b.companyId = 'companyId')

IE 'select all records from this table that have a user in the set of users with companyId = 'companyId', as detailed in another table.

However the above Criteria based statement doesn't work as intended, I believe the setFetchMode is returning the same criteria it was called on and the add statement is adding the company.id = companyId clause to the overall Criteria (ie to tableA).

They meant for this 'add' statement to apply to the FetchMode (ie to the subselect) rather than the Criteria the fetchmode subsequently acts on.

Not being experienced with hibernate criteria statements, I'm not sure if this is possible?

You can accomplish what you're trying to do using aliases:

 criteria.setFetchMode("user", FetchMode.JOIN).createAlias("company","c").add(
                Restrictions.eq("c.id", companyId));

Take a look at this section of the hibernate docs for more info

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