首页 > 解决方案 > 如何在 Spring Boot 应用程序中手动注册非标准化 SQL 函数?

问题描述

我在当前的 spring-boot 项目中使用 JPA 查询。如何添加像GROUP_CONCAT这样的非标准化 SQL 函数?

在我之前的问题之前: 如何在 JPA 查询中以单行逗号分隔列表显示列结果

我发现 GROUP_CONCAT 不是 JPA 查询中的注册函数,但可以通过手动注册来访问。我已经尝试过以下链接,但对我不起作用:

如何在 Spring Boot 应用程序中添加非标准化的 sql 函数?

使用 JPA 和 Hibernate 注册 SQL 函数

https://thoughts-on-java.org/database-functions/

https://vladmihalcea.com/hibernate-sql-function-jpql-criteria-api-query/

1.

public class SqlFunctionsMetadataBuilderContributor
        implements MetadataBuilderContributor {

    @Override
    public void contribute(MetadataBuilder metadataBuilder) {
        metadataBuilder.applySqlFunction(
                "group_concat",
                new StandardSQLFunction(
                        "group_concat",
                        StandardBasicTypes.STRING
                )
        );
    }
}

2.

 public String render(Type firstArgumentType, List arguments, SessionFactoryImplementor factory)
            throws QueryException {
        if (arguments.size() < 1) {
            throw new QueryException(new IllegalArgumentException("group_concat should have at least one arg"));
        }

        StringBuilder builder = new StringBuilder();
        if (arguments.size() > 1 && arguments.get(0).equals("'distinct'")) {
            builder.append("distinct ");
            builder.append(arguments.get(1));
        } else {
            builder.append(arguments.get(0));
        }

        return "group_concat(" + builder.toString() + ")";
    }

3.

@Configuration
public class DataSource {
    @Bean
    public JpaVendorAdapter jpaVendorAdapter() {
        AbstractJpaVendorAdapter adapter = new HibernateJpaVendorAdapter();
        adapter.setShowSql(true);
        adapter.setDatabase(Database.MYSQL);
        // package to CustomMysqlDialect
        adapter.setDatabasePlatform("com.myprojet.admin.configuration.RegisterSqlFunction");
        adapter.setGenerateDdl(false);
        return adapter;
    }
}

    public RegisterSqlFunction() {
        super();

         registerFunction("group_concat, new StandardSQLFunction("group_concat", 
       StandardBasicTypes.STRING));
    }


我除了将 group_concat 与 JPA 查询一起使用。

标签: javamysqlspringjpajpql

解决方案


您可以在我的High-Performance Java Persistence GitHub 存储库中找到一个功能齐全的示例。

在您的情况下,您不需要自定义JpaPlatform. 那应该设置为HibernateJpaPlatform.

您可以MetadataBuilderContributer通过application.properties配置文件以编程方式注册:

hibernate.metadata_builder_contributor=com.vladmihalcea.book.hpjp.SqlFunctionsMetadataBuilderContributor

推荐阅读