如何在Spring Boot应用程序中手动注册非标准的SQL函数? [英] How to register non-standarized SQL functions manually in Spring Boot application?
问题描述
我在当前的spring-boot项目中使用JPA查询.如何添加非标准化的SQL函数,如 GROUP_CONCAT ?
I'm using JPA query in my current spring-boot project. How can I add non-standardized SQL functions like GROUP_CONCAT?
在我之前的问题之前: 如何在JPA查询中的单行逗号分隔列表中显示列结果
Prior, to my previous problem : How to show a column result in a one line comma separated list in JPA query
我发现GROUP_CONCAT不是JPA查询中的注册函数,但是可以通过手动注册来访问它.我已经尝试了以下链接,但对我不起作用:
I found that GROUP_CONCAT is not a registered function in JPA query but could be accessed by registering it manually. I already tried following links but didn't work for me :
如何添加非标准化sql Spring Boot应用程序中有什么功能?
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));
}
除了在JPA查询中使用group_concat之外,我都是这样.
I except using group_concat with JPA query.
推荐答案
您可以在我的高性能Java持久性GitHub存储库.
根据您的情况,您无需自定义JpaPlatform
.应该将其设置为HibernateJpaPlatform
.
In your case, you don't need to customize the JpaPlatform
. That should be set to the HibernateJpaPlatform
.
您可以按照本文或通过application.properties
配置文件:
You can register the MetadataBuilderContributer
either programaticallly as explained in this article or via the application.properties
configuration file:
hibernate.metadata_builder_contributor=com.vladmihalcea.book.hpjp.SqlFunctionsMetadataBuilderContributor
这篇关于如何在Spring Boot应用程序中手动注册非标准的SQL函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!