开发者

How to select the size of a @OneToMany(mappedBy))collection using HQL

开发者 https://www.devze.com 2023-03-27 01:57 出处:网络
First some context and explanation: I have written the following HQL query: select size(childGroups), size(ipts), g.id, g.name, g.status from LogicalGroup g where g.isRoot=true group by g.id, g.name

First some context and explanation:

I have written the following HQL query:

select size(childGroups), size(ipts), g.id, g.name, g.status from LogicalGroup g where g.isRoot=true group by g.id, g.name, g.status

LogicalGroup is an entity with scalar fields: id, name, status, isRoot and two entity collection fields:

  • childGroups

which is a

@OneToMany(mappedBy = "parentGroup")

Set<LogicalGroup>

parentGroup is another field in LogicalGroup. (Each group contains a set of child groups and a parent group).

and

  • ipts

which is a

@OneToMany(mappedBy = "logicalGroup")

Set<IPT>

each IPT has a field logicalGroup denoting the group that it belongs to.

What I would like the query to do, is select the size of the childGroups collection and the size of the ipts collection belonging to the root LogicalGroup (where isRoot==true). There is only ever one group for which isRoot==true.

Logical Group and IPT inherit their id fields from a superclass AbstractEntity. The table structure is such that there is one table per class, (the super class also has its own table). There are no join tables for the relationships between parent/child logical groups or logical group/IPT.


Now the question:

Firstly, I should say that the query returns the scalar values correctly.

The problem is that the query appears to return the size of the LogicalGroup set correctly, but seems to be returning the total number of IPTs in the IPT table, rather than just the ones belonging to the LogicalGroup. Where am I going wrong? Is something wrong with the query or potentially the mapping of the collections?

I turned on SQL logging and the following is generated and executed by Hibernate:

Hibernate: select count(childgroup1_.parentGroup_id) as col_0_0_, 
                  count(ipts2_.logicalGroup_id) as col_1_0_, 
                  logicalgro0_.id as col_2_0_, 
                  logicalgro0_.name >as col_3_0_, 
                  logicalgro0_.status as col_4_0_ from LogicalGroup logicalgro0_ 
           inner join AbstractEntity
                          logicalgro0_1_ on logicalgro0_.id=logicalgro0_1_.id, 
                      LogicalGroup childgroup1_, 
                      IPT ipts2_ 
           where 
               开发者_如何学编程  logicalgro0_.id=childgroup1_.parentGroup_id and 
                 logicalgro0_.id=ipts2_.logicalGroup_id and 
                 logicalgro0_.isRoot=true 
           group by 
                 logicalgro0_.id , logicalgro0_.name , logicalgro0_.status
0

精彩评论

暂无评论...
验证码 换一张
取 消