Friday, May 8, 2020

How to use group_concat in hibernate criteria?

You have two options (depending on your hibernate version).

Override the dialect class any hibernate version

You will need to subclass your dialect to add group_concat()

  1. Introduce the dialect override class

Create the following class somewhere in your app (e.g. util package)

package com.myapp.util;

import org.hibernate.dialect.MySQL5Dialect;
import org.hibernate.dialect.function.StandardSQLFunction;
import org.hibernate.type.StandardBasicTypes;

public class MySQLCustomDialect extends MySQL5Dialect {
    public MySQLCustomDialect() {
        super();
        registerFunction("group_concat", 
            new StandardSQLFunction("group_concat", 
                StandardBasicTypes.STRING));
    }
}
  1. Map the dialect override class to boot properties

        Add the following property to your application.properities

spring.jpa.properties.hibernate.dialect = com.myapp.util.MySQLCustomDialect


Use JPA Metadata Builder Contributor hibernate 5.2.18 or newer only

  1. Introduce metadata builder class

Create the following class, remember to add package & resolve imports.

public class SqlFunctions implements MetadataBuilderContributor {

@Override
public void contribute(MetadataBuilder metadataBuilder) { 
    metadataBuilder.applySqlFunction( "group_concat", 
        new StandardSQLFunction( "group_concat", 
            StandardBasicTypes.STRING ) ); }
}
  1. Map new class in application boot properties

Leave the dialect properties as is

     spring.jpa.properties.hibernate.dialect = org.hibernate.dialect.MySQL5Dialect
     spring.jpa.properties.hibernate.metadata_builder_contributor = com.myapp.util.SqlFunctions

No comments:

Post a Comment

Recent Post

Databricks Delta table merge Example

here's some sample code that demonstrates a merge operation on a Delta table using PySpark:   from pyspark.sql import SparkSession # cre...