Home > Software design >  Hibernate 6 SQLFunctionTemplate Alternative
Hibernate 6 SQLFunctionTemplate Alternative

Time:12-31

We have HibernateMetadataBuilderContributor Like below. Which works in Hibernate 5 or Spring boot 2.7. But not working when we migrate to Hibernate 6 or Spring boot 3.

public class HibernateMetadataBuilderContributor implements MetadataBuilderContributor {

    public static final String STRING_AGG = "string_agg";
    public static final String STRING_AGG_ORDER_BY = "string_agg_order_by";
    public static final String STRING_AGG_DISTINCT = "string_agg_distinct";

    @Override
    public void contribute(final MetadataBuilder metadataBuilder) {
        metadataBuilder.applySqlFunction(STRING_AGG, new SQLFunctionTemplate(StandardBasicTypes.STRING, "string_agg(?1, ?2)"));
        metadataBuilder.applySqlFunction(STRING_AGG_ORDER_BY, new SQLFunctionTemplate(StandardBasicTypes.STRING, "string_agg(?1, ?2 order by ?3)"));
        metadataBuilder.applySqlFunction(STRING_AGG_DISTINCT, new SQLFunctionTemplate(StandardBasicTypes.STRING, "string_agg(distinct ?1, ?2)"));

    }
}

SQLFunctionTemplate is not found in Hibernate 6, what is the alternative.

CodePudding user response:

First: you don't need to do this in H6!

HQL now comes with a built-in listagg() function which is automatically translated to string_agg() on those databases where that's what it's called. Please check the User Guide chapter on HQL for a full list of built-in portable functions.

https://docs.jboss.org/hibernate/orm/6.2/userguide/html_single/Hibernate_User_Guide.html#hql-aggregate-functions-orderedset

Now, with that said...

The equivalent interface to SQLFunction in H6 is SqmFunctionDescriptor, which has lots of built-in implementations you could look at for inspiration, including PatternBasedSqmFunctionDescriptor.

But the basic, simplified, "user-friendly" implementation we provide is still org.hibernate.dialect.function.StandardSQLFunction, which has now been adapted to the new, much more-powerful SqmFunctionDescriptor framwork.

CodePudding user response:

Using in the below way seems working.

new PatternBasedSqmFunctionDescriptor(
                new PatternRenderer(pattern),
                null,
                null,
                null,
                name,
                FunctionKind.NORMAL,
                null
        );
  • Related