Hibernate 5.3: register SQL functions at runtime

Hello,

it does exist a way to register custom SQL functions at runtime in HIbernate 5.3? It seems that since this changeset[1] was introduced, is not possible.

Correct me if I’m wrong, but the current options to register a custom SQL function in Hibernate are the following ones:

  1. Create a custom dialect and register the functions on the constructor.
  2. Get the Configuration object when the app starts and register the SQL functions.
  3. Use a MetadataBuilderInitializer

But as far as I know none of this options allows to add SQL functions after Hibernate has been set up.

What do you think? What is the recommended approach in this case?

Thank you in advance.

[1] https://github.com/hibernate/hibernate-orm/commit/52589379e1a93c372a323a9334d12b2f31dc0a7a

As indicated by Christian’s comment, for the moment there is no way to add those functions dynamically.

You should create a Jira issue and provide some context about your use case and why you can’t provide those via Dialect.

Done: https://hibernate.atlassian.net/browse/HHH-12528

Thank you for the response.

Good news. Sing Hibernate ORM 5.2.18 and 5.3.1, you can now register functions dynamically.

Just provide a custom MetadataBuilderContributor:

public class SqlFunctionsMetadataBuilderContributor 
        implements MetadataBuilderContributor {
         
    @Override
    public void contribute(MetadataBuilder metadataBuilder) {
        metadataBuilder.applySqlFunction(
            "group_concat",
            new StandardSQLFunction(
                "group_concat", 
                StandardBasicTypes.STRING
            )
        );
    }
}

And supply the MetadataBuilderContributor like this.

<property>
    name="hibernate.metadata_builder_contributor" 
    value="com.vladmihalcea.book.hpjp.hibernate.query.function.SqlFunctionsMetadataBuilderContributor"
</property>

For more details, chekc out this article.

Hello,

@vlad thanks for the information and great article! :grinning:

Just to let you know, the solution that we finally took as at the moment we targeted this problem, this feature (registering the functions at runtime) was not available for us, is providing an API for our developers to register the SQL functions just at server startup.

We are using a different approach from the ones mentioned in the article: to use the Configuration class.

We are retrieving the map of SQL functions and internally we are adding those functions with the addSqlFunction method of the Configuration class.

Regards.