Hibernate Criteria API - how to order by collection size?

前端 未结 3 1121
走了就别回头了
走了就别回头了 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:32

    You could probably so this by defining a "derived property" on your entity, which would be a read-only property which returns the size of the collection inside that entity. The easiest way to define a derived property is documented here:

    update, insert (optional - defaults to true): specifies that the mapped columns should be included in SQL UPDATE and/or INSERT statements. Setting both to false allows a pure "derived" property whose value is initialized from some other property that maps to the same column(s), or by a trigger or other application.

    Once the property is defined, you should be able to use the property name as an order clause in the criteria API, just like any other property. I haven't tried this myself, though.

    If it works, it'll likely be done as an in-memory sort, since it won't be able to map it to SQL. If this is a problem, then the same link above documents how to implement a derived property using a custom SQL fragment:

    A powerful feature is derived properties. These properties are by definition read-only. The property value is computed at load time. You declare the computation as an SQL expression. This then translates to a SELECT clause subquery in the SQL query that loads an instance:

提交回复
热议问题