简体   繁体   English

结合两个HQL查询

[英]Combinate two HQL queries

I have two entities with the following fields: 我有两个具有以下字段的实体:

Application: applicationId, name, description, lastVersion (transient)

and

ApplicationVersion: applicationVersionId, application, versionName, creationDate

I'm trying to get a Collection with all applications and, for the applications with one or more version, put the versionName of the ApplicationVersion with the most recent creationDate in the transient field lastVersion. 我正在尝试获取所有应用程序的集合,对于具有一个或多个版本的应用程序,将ApplicationVersion的versionName和最新的creationDate放在过渡字段lastVersion中。

At this moment i'm doing this with two hql queries: 目前,我正在使用两个hql查询来执行此操作:

This one to get all the unversioned applications: 这是所有未版本控制的应用程序:

SELECT a from Application a where a not in (select b.application from ApplicationVersion b)

And this to get the last version of the versioned ones: 这是获取版本化版本的最新版本:

select b from ApplicationVersion b where b.creationDate = (select max(bb.creationDate) from ApplicationVersion bb where bb.application = b.application)

After executing both, I iterate over the second resultset and add this applications and their last eversion to the first resulset. 执行完这两个步骤之后,我遍历第二个结果集,并将此应用程序及其最后一次转换添加到第一个结果集。

But I want to combinate both queries in something like this (this is not working at all): 但是我想以这样的方式组合两个查询(这根本不起作用):

select new foo.bar.Application(a.applicationId, a.name, a.description, b.version) from Application a, ApplicationVersion b where 
(a not in (select bb.application from ApplicationVersion bb)) 
or 
(a=b.application and b.creationDate = (select max(bb.creationDate) from ApplicationVersion bb where bb.application = b.application))

Is there any (efficient) way to combinate both queries and execute only one, and avoid do the iteration programmatically? 是否有任何(有效的)方式可以合并两个查询并仅执行一个查询,并避免以编程方式进行迭代?

Yes, you could make it better, when your children records have a parent, you have to use 是的,您可以做得更好,当您的孩子记录有父母时,您必须使用

join fetch 

for example, you have Application, and ApplicationVersion, then: 例如,您有Application和ApplicationVersion,然后:

from ApplicationVersion av
join fetch av.application ap
where ap.applicationId = :id

With this way, you have a relation between both objects and you can filter using where expression, be sure your ApplicationVersion has an attribute referencing Application object. 这样,您就可以在两个对象之间建立关系,并且可以使用where表达式进行过滤,请确保ApplicationVersion具有引用Application对象的属性。

Hope it helps to you. 希望对您有帮助。

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

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