简体   繁体   中英

Hibernate left join fetch - get only an ID list of the first table

I have the following HQL query which works fine, however it returns a list of full FooD objects. I only need the ID of the FooD objects as I need to have faster query. Please not that in Hibernate mappings, FooD has a many-to-one relationship with FooB.

hqlQuery = "from FooD d left join fetch d.bill where d.ts < :ts"

I have then tried to get only the ID using the same kind of HQL query:

hqlQuery = "SELECT d.id from FooD d left join fetch d.bill where d.ts < :ts"

I got a "query specified join fetching, but the owner of the fetched association was not present in the select list".

I have then converted the query to regular Oracle SQL to get only FooD.ID:

sqlQuery = "SELECT d.id from FooD d LEFT OUTER JOIN FooB b on d.foodId=b.id where d.ts < :ts"

I have then mapped FooD and FooB objects like this:

sqlQuery.addEntity(FooD.class);
sqlQuery.addEntity(FooB.class);

and then get the resulting list by calling:

hSession.createSQLQuery(sql).setTimestamp("ts", ts).list();

But got the following error: "unexpected token: on near line 1".

Does someone know how to do get only the ID of FooD when doing a left outer join on FooB using Hibernate?

Update:

I didn't test it, but this should do the trick

SELECT d.id from FooD d inner join d.bill where d.ts < :ts

when you add LEFT you make it an outer join implicitly, and there is no need to initialize bill if all you need is to join by keys


Hibernate requires the object to be in the select clause to do any eager join fetches on it

But since you have no select or where clauses on d.bill, why do you need to fetch it anyway?

If all you need is the id, why not do this, there is no reason for the redundant join:

hqlQuery = "SELECT d.id from FooD d where d.ts < :ts" 

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