HOW TO ORDER BY A CUSTOM SQL FORMULA/EXPRESSION WHEN USING HIBERNATE CRITERIA API

本文介绍了一种在Hibernate中使用动态生成SQL表达式进行排序的方法。通过扩展Hibernate的Order类,实现了自定义OrderBySqlFormula类,允许用户指定任意SQL公式进行排序。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

In our current project we are using Spring + Hibernate Annotations.

Today I needed to use something like:


SELECT DISTINCT t.id FROM MyClass t
 WHERE .....
 ORDER BY (a + b) DESC


where a and b are properties of MyClass (columns in the “my_class” table).

The “where …” expression must be generated dynamically based on the user input, so we are using Criteria API to generate the query as such:


Criteria criteria = getSession().createCriteria(MyClass.class);
criteria.setProjection(Projections.distinct(Projections.id()));
 
// Some custom dynamic conditions
criteria.add(Restrictions.gt("createdDate", afterDate));
criteria.add(Restrictions.in("state", approvedStates));
criteria.add(Restrictions.isNull("deletedDate"));
if (includedCategories != null || excludedCategories != null) {
    Criteria categoryCriteria = criteria.createCriteria("category");
    if (includedCategories != null) {
        for (String categoryPrefix : includedCategories) {
            categoryCriteria.add(Restrictions.like("path", categoryPrefix + "%"));
        }
    }
    if (excludedCategories != null) {
        for (String categoryPrefix : excludedCategories) {
            categoryCriteria.add(Restrictions.not(Restrictions.like("path", categoryPrefix + "%")));
        }
    }
}
 
criteria.add(Restrictions.sqlRestriction("(a + b) > 1"));
 
// Custom ordering by some SQL formula/expression
criteria.addOrder(Order.desc("a + b"));
 
return criteria.list();


Now, the problem is that the class Order does not support custom SQL formula/expression…

So my solution was to derive my own class as such:

package ro.tremend.util.hibernate;
 
import org.hibernate.criterion.Order;
import org.hibernate.criterion.CriteriaQuery;
import org.hibernate.Criteria;
import org.hibernate.HibernateException;
 
/**
 * Extends {@link org.hibernate.criterion.Order} to allow ordering by an SQL formula passed by the user.
 * Is simply appends the <code>sqlFormula</code> passed by the user to the resulting SQL query, without any verification.
 * @author Sorin Postelnicu
 * @since Jun 10, 2008
 */
public class OrderBySqlFormula extends Order {
    private String sqlFormula;
 
    /**
     * Constructor for Order.
     * @param sqlFormula an SQL formula that will be appended to the resulting SQL query
     */
    protected OrderBySqlFormula(String sqlFormula) {
        super(sqlFormula, true);
        this.sqlFormula = sqlFormula;
    }
 
    public String toString() {
        return sqlFormula;
    }
 
    public String toSqlString(Criteria criteria, CriteriaQuery criteriaQuery) throws HibernateException {
        return sqlFormula;
    }
 
    /**
     * Custom order
     *
     * @param sqlFormula an SQL formula that will be appended to the resulting SQL query
     * @return Order
     */
    public static Order sqlFormula(String sqlFormula) {
        return new OrderBySqlFormula(sqlFormula);
    }
}




Now, to use the custom ordering, I included the following line:



 criteria.addOrder(OrderBySqlFormula.sqlFormula("(a + b) desc"));



数据集介绍:野生动物目标检测数据集 一、基础信息 数据集名称:野生动物目标检测数据集 图片数量: - 训练集:11,787张图片 - 验证集:643张图片 - 测试集:431张图片 总计:12,861张真实场景图片 分类类别: - Elephant(象):陆生大型哺乳动物,包含多种自然环境中的活动姿态。 - Bear(熊):涵盖不同种类的熊科动物,包括静态及运动状态。 - Cheetah(猎豹):强调高速运动状态下的动态捕捉样本。 - Deer(鹿):包含林地和草原环境中的鹿群及个体样本。 - Fox(狐):涵盖多种狐狸品种的多样化行为模式。 标注格式: YOLO格式,包含标准化的归一化坐标标注,可直接适配YOLOv5/v7/v8等主流检测框架。 数据特性: 涵盖航拍、地面视角等多角度拍摄的野生动物图像,包含昼夜不同光照条件下的样本。 二、适用场景 生态监测系统开发: 支持构建自然保护区智能监测系统,实时检测野生动物活动轨迹并统计种群分布。 自动驾驶环境感知: 用于训练车辆视觉系统识别道路周边野生动物的能力,提升行车安全系数。 野生动物研究分析: 提供动物行为学研究的结构化数据支撑,支持物种活动模式分析与栖息地研究。 安防监控系统升级: 适用于农场、林区等场景的智能安防系统开发,精准识别潜在动物威胁。 三、数据集优势 多物种覆盖: 包含5类高关注度野生动物,覆盖陆地生态系统的关键指示物种。 场景多样性: 数据采集涵盖丛林、草原、山地等多种自然生境,增强模型泛化能力。 标注专业性: 经动物学专家校验的精准边界框标注,确保目标定位与分类准确性。 任务适配性: 原生YOLO格式支持快速迁移至目标检测、行为分析、密度估计等衍生任务。 规模优势: 超万级标注样本量,有效支撑深度神经网络的特征学习需求。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值