Hibernate Criteria Order By

[亡魂溺海] 提交于 2019-11-30 18:03:04

If you want to return a list of entities or properties in combination with a count you will need a group by. In criteria this is done through ProjectionList and Projections. e.g.

    final ProjectionList props = Projections.projectionList();
    props.add(Projections.groupProperty("giftID"));
    props.add(Projections.groupProperty("giftName"));
    props.add(Projections.count("giftID"), "count"); //create an alias for the count
    crit.setProjection(props);

    crit.add(Order.desc("count")); //use the count alias to order by

However, since you're using ProjectionList you will also need to use AliasToBeanConstructorResultTransformer.

Note for anyone else that comes through here looking to order by a property/column:

When using the approaches mentioned here, no results were found. The fix was to use criteria.addOrder(Order.asc(property)); instead. Notice the difference is to use addOrder, rather than add;

I've had this issue several times after running here for a quick reference.

You have a one-to-many relationship from Gift to ClickThrough so I assume each ClickThrough is a record with some datetime or other information associated with it. In this case, I would add a "count" field to your mapping file and attach the ordering to the criterion:

criterion.add(Order.asc(count)))

The mapping property looks something like:

<property name="count" type="integer" formula="(select count(*) from Gift g inner join ClickThrough ct on ct.gift_id=g.id where g.id=ID)"/>

If you can't or don't want to change the mapping file, you could use Collections.sort() with a Comparator though it seems less efficient having to return so much data from the DB.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!