java - 如何在 Spring Boot 应用程序中手动注册非标准化 SQL 函数?
问题描述
我在当前的 spring-boot 项目中使用 JPA 查询。如何添加像GROUP_CONCAT这样的非标准化 SQL 函数?
在我之前的问题之前: 如何在 JPA 查询中以单行逗号分隔列表显示列结果
我发现 GROUP_CONCAT 不是 JPA 查询中的注册函数,但可以通过手动注册来访问。我已经尝试过以下链接,但对我不起作用:
如何在 Spring Boot 应用程序中添加非标准化的 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 查询一起使用。
解决方案
您可以在我的High-Performance Java Persistence GitHub 存储库中找到一个功能齐全的示例。
在您的情况下,您不需要自定义JpaPlatform
. 那应该设置为HibernateJpaPlatform
.
您可以MetadataBuilderContributer
通过application.properties
配置文件以编程方式注册:
hibernate.metadata_builder_contributor=com.vladmihalcea.book.hpjp.SqlFunctionsMetadataBuilderContributor
推荐阅读
- python - 从包含 x、y、id 列的 pandas 数据中分别绘制点和线
- amazon-web-services - 为什么 API 网关会损坏我的二进制文件?
- nix - 如何在不构建 Nix 表达式的情况下知道构建计划和存储路径?
- c# - 如何从托管在 IIS 上的 .net 代码访问密钥保管库机密
- c# - Jqgrid上传图像不将数据对象传递到数据库
- node.js - 在视图中分组我的数据 - nodejs
- javascript - 两个ajax调用的无限循环不断加载页面而不调用成功函数
- c# - 使用 Dapper 水合复杂对象
- javascript - 跨站点脚本(基于 DOM)的打嗝问题
- javascript - 复选框的奇怪 onclick 行为。选择复选框项目时尝试写入浏览器控制台