问题
I'm using JPA query in my current spring-boot project. How can I add non-standardized SQL functions like GROUP_CONCAT?
Prior, to my previous problem : How to show a column result in a one line comma separated list in JPA query
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 :
How to add non-standardized sql functions in Spring Boot application?
Registering a SQL function with JPA and Hibernate
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));
}
I except using group_concat with JPA query.
回答1:
You can find a fully functional example in my High-Performance Java Persistence GitHub repository.
In your case, you don't need to customize the JpaPlatform. That should be set to the HibernateJpaPlatform.
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
来源:https://stackoverflow.com/questions/57385780/how-to-register-non-standarized-sql-functions-manually-in-spring-boot-applicatio