You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Hibernate 6中SQLFunctionTemplate的替代方案咨询

Hibernate 6/Spring Boot 3 替换SQLFunctionTemplate的方案

在Hibernate 6及Spring Boot 3环境中,原Hibernate 5的SQLFunctionTemplate类已被移除,你可以使用FunctionTemplate类来替代,实现相同的自定义SQL函数注册功能。

修改后的代码实现

import org.hibernate.boot.MetadataBuilder;
import org.hibernate.boot.spi.MetadataBuilderContributor;
import org.hibernate.query.sqm.function.FunctionTemplate;
import org.hibernate.type.StandardBasicTypes;

public class HibernateMetadataBuilderContributor implements MetadataBuilderContributor {

    public static final String STRING_AGG = "string_agg";
    public static final String STRING_AGG_ORDER_BY = "string_agg_order_by";
    public static final String STRING_AGG_DISTINCT = "string_agg_distinct";

    @Override
    public void contribute(final MetadataBuilder metadataBuilder) {
        // 注册基础string_agg函数
        metadataBuilder.applySqlFunction(STRING_AGG, 
                FunctionTemplate.create(StandardBasicTypes.STRING, "string_agg(?1, ?2)"));
        // 注册带排序的string_agg函数
        metadataBuilder.applySqlFunction(STRING_AGG_ORDER_BY, 
                FunctionTemplate.create(StandardBasicTypes.STRING, "string_agg(?1, ?2 order by ?3)"));
        // 注册带distinct的string_agg函数
        metadataBuilder.applySqlFunction(STRING_AGG_DISTINCT, 
                FunctionTemplate.create(StandardBasicTypes.STRING, "string_agg(distinct ?1, ?2)"));
    }
}

关键说明

  • FunctionTemplate位于org.hibernate.query.sqm.function包下,是Hibernate 6中用于注册模板化SQL函数的官方替代类。
  • 用法和原SQLFunctionTemplate一致,通过create方法指定函数的返回类型(如StandardBasicTypes.STRING)和SQL模板字符串,模板中的?n对应函数调用时的第n个参数。
  • 如果需要注册更复杂的自定义函数(比如需要处理参数类型转换、动态生成SQL逻辑),可以实现SQLFunction接口,或使用SqlFunctionDescriptorBuilder来构建更灵活的函数定义。

内容的提问来源于stack exchange,提问作者Jana

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.06 20:50:31