gpt4 book ai didi

Hibernate Criteria API - 如何按集合大小排序?

转载 作者:行者123 更新时间:2023-12-03 12:05:17 25 4
gpt4 key购买 nike

假设我有类用户和用户组。有一个可选的 1-many group 到用户关联,并且关联从双方映射(UserGroup 侧通过名为“members”的属性,这是一个 HashSet,User 侧通过属性“group”)。

使用 Criteria API,我如何查询所有组,按组成员数排序?

(编辑)当我问这个问题时,我应该指出分页是在 SQL 中执行的,所以如果可能的话,排序也应该在 SQL 中执行。

最佳答案

默认情况下无法使用 Citeria API,但您可以扩展 org.hibernate.criterion.Order 类。
这篇文章是关于如何扩展该类:http://blog.tremend.ro/2008/06/10/how-to-order-by-a-custom-sql-formulaexpression-when-using-hibernate-criteria-api

我的解决方案是:

public class SizeOrder extends Order {

protected String propertyName;
protected boolean ascending;

protected SizeOrder(String propertyName, boolean ascending) {
super(propertyName, ascending);
this.propertyName = propertyName;
this.ascending = ascending;
}

public String toSqlString(Criteria criteria, CriteriaQuery criteriaQuery) throws HibernateException {
String role = criteriaQuery.getEntityName(criteria, propertyName) + '.' + criteriaQuery.getPropertyName(propertyName);
QueryableCollection cp = (QueryableCollection) criteriaQuery.getFactory().getCollectionPersister(role);

String[] fk = cp.getKeyColumnNames();
String[] pk = ((Loadable) cp.getOwnerEntityPersister())
.getIdentifierColumnNames();
return " (select count(*) from " + cp.getTableName() + " where "
+ new ConditionFragment()
.setTableAlias(
criteriaQuery.getSQLAlias(criteria, propertyName)
).setCondition(pk, fk)
.toFragmentString() + ") "
+ (ascending ? "asc" : "desc");
}

public static SizeOrder asc(String propertyName) {
return new SizeOrder(propertyName, true);
}
public static SizeOrder desc(String propertyName) {
return new SizeOrder(propertyName, false);
}
}

toSqlString 方法基于 org.hibernate.criterion.SizeExpression 类。 (来源: http://javasourcecode.org/html/open-source/hibernate/hibernate-3.6.0.Final/org/hibernate/criterion/SizeExpression.java.html)

示例用法:
hibernateSession.createCriteria(UserGroup.class).addOrder( SizeOrder.asc("members") ).list();

这将列出按成员大小升序排列的用户组,其中“成员”是 UserGroup 实体中的用户集合。

关于Hibernate Criteria API - 如何按集合大小排序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1254306/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com