1 Aralık 2022 Perşembe

MetadataBuilderContributor Arayüzü - Custom SQL Metodu İçindir

Giriş
Açıklaması şöyle
Since Hibernate 5.2.18, you can use the MetadataBuilderContributor utility to customize the MetadataBuilder even if you are bootstrapping via JPA.
Örnek
Şöyle yaparız
import org.hibernate.boot.MetadataBuilder;
import org.hibernate.boot.spi.MetadataBuilderContributor; import org.hibernate.dialect.function.SQLFunctionTemplate; import org.hibernate.type.BooleanType; public class SQLFunctionContributor implements MetadataBuilderContributor { @Override public void contribute(MetadataBuilder metadataBuilder) { metadataBuilder.applySqlFunction("json_contains_key", new SQLFunctionTemplate(BooleanType.INSTANCE, "JSON_CONTAINS(?1, JSON_QUOTE(?2))")); } }
Açıklaması şöyle
In the above snippet, I am overriding the contribute method by providing one of the MySQL JSON functions.

The JSON_CONTAINS() function checks whether one JSON document contains another JSON document.

JSON_CONTAINS(target_json, candidate_json)

Parameters

target_jsonRequired. A JSON document.

candidate_jsonRequired. The included JSON document.

As you see, I have created a custom key “json_contains_key”. This actually will be used in Criteria API or Query DSL and will be parsed by Hibernate as JSON_CONTAINS().

And provide the custom MetadataBuilderContributor to Hibernate via the hibernate.metadata_builder_contributor configuration property.

spring.jpa.properties.hibernate.metadata_builder_contributor=com.abhicodes.customdialect.util.SQLFunctionContributor