简体   繁体   English

休眠左连接获取-仅获取第一个表的ID列表

[英]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. 我有以下运行良好的HQL查询,但是它返回完整FooD对象的列表。 I only need the ID of the FooD objects as I need to have faster query. 我只需要FooD对象的ID,因为我需要更快的查询。 Please not that in Hibernate mappings, FooD has a many-to-one relationship with FooB. 请不要在Hibernate映射中,FooD与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: 然后,我尝试使用相同类型的HQL查询仅获取ID:

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: 然后,我已将查询转换为常规Oracle SQL,以仅获取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: 然后,我已经映射了FooD和FooB对象,如下所示:

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". 但出现以下错误: "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? 使用Hibernate在FooB上进行左外部联接时,有人知道如何仅获取FooD的ID吗?

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 当您添加LEFT时,将其隐式地设置为外部联接,并且如果您需要的只是通过键联接,则无需初始化bill。


Hibernate requires the object to be in the select clause to do any eager join fetches on it Hibernate要求对象在select子句中,以便对其进行任何渴望的连接提取

But since you have no select or where clauses on d.bill, why do you need to fetch it anyway? 但是,由于d.bill上没有select或where子句,为什么仍然需要获取它?

If all you need is the id, why not do this, there is no reason for the redundant join: 如果您只需要id,为什么不这样做,则没有理由进行冗余连接:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM