Hibernate Criteria API - how to order by collection size?

前端 未结 3 1113
走了就别回头了
走了就别回头了 2021-01-01 03:12

Assuming I have classes User and UserGroup. There is an optional 1-many group to user association and the association is mapped from both sides (the UserGroup side via a pro

3条回答
  •  悲哀的现实
    2021-01-01 03:23

    Another option would be to use the @Formula annotation which is basically the equivalent of creating a nested select so you can get at your counts.

    On your DB objects property / member in question (which you should create), add the annotation to the getter like:

    @Formula("(SELECT COUNT(TABLE_NAME.ID) FROM TABLE WHERE whatever...)") public long getNewProperty{ return newProperty; }

    Then target the member directly to get hold of your count values...

    Note: Be aware that when specifying the sql within the formula annotation, you must specify the field names directly when referencing the current objects table (this) as hibernate deals with this itself. So in your WHERE clause just use ID or whatever on its own when referencing the current objects table which I suspect is UserGroup.

    I had to have a setter for my new property in order for hibernate to work and prevent the compiler from complaining.

    There may be other clever ways of using @Formula, but I'm quite new to this and there doesn't appear to be very much documentation on the subject...

    If you've never used nested SELECTS before, it might be an idea for you to just recreate in sql first - that helped me.

    Hope this helps

提交回复
热议问题