<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by BIDS Salvaterra on Medium]]></title>
        <description><![CDATA[Stories by BIDS Salvaterra on Medium]]></description>
        <link>https://medium.com/@bidsalvaterra51?source=rss-434e22aca425------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*kepx05usXrKqhHdE.jpg</url>
            <title>Stories by BIDS Salvaterra on Medium</title>
            <link>https://medium.com/@bidsalvaterra51?source=rss-434e22aca425------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Wed, 02 Dec 2026 04:38:59 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@bidsalvaterra51/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Custom SQL Functions in Hibernate 6.5.3: A Complete Implementation Guide]]></title>
            <link>https://medium.com/@bidsalvaterra51/custom-sql-functions-in-hibernate-6-5-3-a-complete-implementation-guide-f416f88dc274?source=rss-434e22aca425------2</link>
            <guid isPermaLink="false">https://medium.com/p/f416f88dc274</guid>
            <category><![CDATA[hibernate-jpa]]></category>
            <category><![CDATA[spring-boot]]></category>
            <category><![CDATA[java-spring-boot]]></category>
            <category><![CDATA[hibernate]]></category>
            <category><![CDATA[hibernate-tutorial]]></category>
            <dc:creator><![CDATA[BIDS Salvaterra]]></dc:creator>
            <pubDate>Sat, 23 Nov 2024 17:04:18 GMT</pubDate>
            <atom:updated>2024-12-24T12:55:39.635Z</atom:updated>
            <cc:license>https://creativecommons.org/publicdomain/mark/1.0/</cc:license>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mmHstnkPdPbS9UdjpKwS9A.jpeg" /></figure><p>When working with JPA and Hibernate, you often find yourself in situations where standard JPQL functions aren’t enough. Whether you need to leverage database-specific features, implement complex business logic at the database level, or optimize performance, custom SQL functions can be a powerful tool in your arsenal.</p><p>In this guide, we’ll explore how to implement custom SQL functions in Hibernate 6.5.3 using the FunctionContributor approach, which is now the recommended way to extend Hibernate&#39;s function capabilities. We&#39;ll be using PostgreSQL 16 for our examples.</p><h4>Understanding ServiceLoader in Java</h4><p>Before diving into the implementation, it’s important to understand Java’s ServiceLoader mechanism, as it’s fundamental to how Hibernate discovers our custom functions.</p><p>The ServiceLoader is a Java utility class that helps in implementing a service provider framework. It enables you to:</p><ol><li>Define service interfaces or abstract classes</li><li>Create implementations of these services</li><li>Make the implementations discoverable at runtime</li></ol><p>Here’s how it works:</p><ol><li>You create a file in META-INF/services/</li><li>The file name is the fully qualified name of your service interface</li><li>The file contains the fully qualified names of your implementations</li><li>ServiceLoader discovers and loads these implementations at runtime</li></ol><p>In our case:</p><ul><li>Service Interface: org.hibernate.boot.model.FunctionContributor</li><li>Implementation: Our custom contributor class</li><li>Location: META-INF/services/org.hibernate.boot.model.FunctionContributor</li></ul><p>This approach provides:</p><ul><li>Loose coupling between Hibernate and our functions</li><li>Dynamic discovery of functions at runtime</li><li>Clean separation of concerns</li><li>Easy addition of new functions</li></ul><h3>Our Example Scenario</h3><p>For this tutorial, we’ll implement two custom functions:</p><ol><li>first_word(text) - Extracts the first word from a text string</li><li>calculate_distance(point, point) - Calculates the distance between two points</li></ol><p>Here’s how they look in PostgreSQL:</p><pre>CREATE OR REPLACE FUNCTION public.first_word(input_text text)<br>RETURNS text<br>LANGUAGE plpgsql<br>AS $$<br>DECLARE<br>    first_space integer;<br>BEGIN<br>    first_space := position(&#39; &#39; in input_text);<br>    IF first_space = 0 THEN<br>        RETURN input_text;<br>    ELSE<br>        RETURN substring(input_text from 1 for first_space - 1);<br>    END IF;<br>END;<br>$$;<br><br>CREATE OR REPLACE FUNCTION public.calculate_distance(<br>    point1 point,<br>    point2 point<br>)<br>RETURNS double precision<br>LANGUAGE plpgsql<br>AS $$<br>BEGIN<br>    RETURN point(point1[0] - point2[0], point1[1] - point2[1])::point &lt;-&gt; point(0,0);<br>END;<br>$$;</pre><h4>The FunctionContributor Approach</h4><p>Starting with Hibernate 6.x, the recommended way to register custom functions is through the FunctionContributor interface. This approach:</p><ul><li>Uses Java’s ServiceLoader mechanism for automatic discovery</li><li>Provides better integration with Hibernate’s internals</li><li>Offers cleaner separation of concerns</li><li>Makes function registration more maintainable</li></ul><p>The basic structure involves:</p><ol><li>Implementing the FunctionContributor interface</li><li>Creating function descriptor classes</li><li>Registering with ServiceLoader</li></ol><p>In the next part of this article, we’ll dive into the actual implementation of these functions in Hibernate 6.5.3, including:</p><ul><li>Setting up the project structure</li><li>Implementing function descriptors</li><li>Handling parameter types</li><li>Registration with ServiceLoader</li><li>Usage in repositories</li></ul><h3>Implementation Steps</h3><p>Let’s implement our custom functions step by step.</p><h3>1. Project Setup</h3><p>First, ensure you have the correct dependencies in your pom.xml:</p><pre>&lt;dependency&gt;<br>    &lt;groupId&gt;org.hibernate.orm&lt;/groupId&gt;<br>    &lt;artifactId&gt;hibernate-core&lt;/artifactId&gt;<br>    &lt;version&gt;6.5.3.Final&lt;/version&gt;<br>&lt;/dependency&gt;<br>&lt;dependency&gt;<br>    &lt;groupId&gt;org.postgresql&lt;/groupId&gt;<br>    &lt;artifactId&gt;postgresql&lt;/artifactId&gt;<br>    &lt;version&gt;42.7.4&lt;/version&gt;<br>&lt;/dependency&gt;</pre><h3>2. Function Implementations</h3><p>Let’s create our function descriptor implementations. We’ll create a separate class for each function to maintain clean code organization.</p><pre>// File: src/main/java/com/example/hibernate/functions/FirstWordFunction.java<br>public class FirstWordFunction extends AbstractSqmSelfRenderingFunctionDescriptor {<br>    <br>    public FirstWordFunction(TypeConfiguration typeConfiguration) {<br>        super(<br>            &quot;first_word&quot;,                    // Function name<br>            FunctionKind.NORMAL,             // Regular SQL function<br>            StandardArgumentsValidators.exactly(1), // One argument<br>            StandardFunctionReturnTypeResolvers.invariant(<br>                typeConfiguration.getBasicTypeRegistry().resolve(StandardBasicTypes.STRING)<br>            ),<br>            null<br>        );<br>    }<br><br>    private void renderer(<br>            SqlAppender sqlAppender,<br>            List&lt;? extends SqlAstNode&gt; sqlAstArguments,<br>            SqlAstTranslator&lt;?&gt; translator) {<br>            <br>        sqlAppender.appendSql(&quot;first_word(&quot;);<br>        translator.render(sqlAstArguments.get(0), SqlAstNodeRenderingMode.DEFAULT);<br>        sqlAppender.appendSql(&quot;)&quot;);<br>    }<br><br>    @Override<br>    public void render(<br>            SqlAppender sqlAppender,<br>            List&lt;? extends SqlAstNode&gt; sqlAstArguments,<br>            ReturnableType&lt;?&gt; returnType,<br>            SqlAstTranslator&lt;?&gt; translator) {<br>        renderer(sqlAppender, sqlAstArguments, translator);<br>    }<br>}<br><br>// File: src/main/java/com/example/hibernate/functions/CalculateDistanceFunction.java<br>public class CalculateDistanceFunction extends AbstractSqmSelfRenderingFunctionDescriptor {<br>    <br>    public CalculateDistanceFunction(TypeConfiguration typeConfiguration) {<br>        super(<br>            &quot;calculate_distance&quot;,            // Function name<br>            FunctionKind.NORMAL,             // Regular SQL function<br>            StandardArgumentsValidators.exactly(2), // Two arguments<br>            StandardFunctionReturnTypeResolvers.invariant(<br>                typeConfiguration.getBasicTypeRegistry().resolve(StandardBasicTypes.DOUBLE)<br>            ),<br>            null<br>        );<br>    }<br><br>    private void renderer(<br>            SqlAppender sqlAppender,<br>            List&lt;? extends SqlAstNode&gt; sqlAstArguments,<br>            SqlAstTranslator&lt;?&gt; translator) {<br>            <br>        sqlAppender.appendSql(&quot;calculate_distance(&quot;);<br>        <br>        // First point<br>        sqlAppender.appendSql(&quot;point(&quot;);<br>        translator.render(sqlAstArguments.get(0), SqlAstNodeRenderingMode.DEFAULT);<br>        sqlAppender.appendSql(&quot;)&quot;);<br>        <br>        sqlAppender.appendSql(&quot;, &quot;);<br>        <br>        // Second point<br>        sqlAppender.appendSql(&quot;point(&quot;);<br>        translator.render(sqlAstArguments.get(1), SqlAstNodeRenderingMode.DEFAULT);<br>        sqlAppender.appendSql(&quot;)&quot;);<br>        <br>        sqlAppender.appendSql(&quot;)&quot;);<br>    }<br><br>    @Override<br>    public void render(<br>            SqlAppender sqlAppender,<br>            List&lt;? extends SqlAstNode&gt; sqlAstArguments,<br>            ReturnableType&lt;?&gt; returnType,<br>            SqlAstTranslator&lt;?&gt; translator) {<br>        renderer(sqlAppender, sqlAstArguments, translator);<br>    }<br>}</pre><h3>3. Function Contributor Implementation</h3><p>Now, let’s create our contributor that registers these functions:</p><pre>// File: src/main/java/com/example/hibernate/functions/CustomFunctionContributor.java<br>public class CustomFunctionContributor implements FunctionContributor {<br>    <br>    @Override<br>    public void contributeFunctions(FunctionContributions contributions) {<br>        // Register first_word function<br>        contributions.getFunctionRegistry().register(<br>            &quot;first_word&quot;,<br>            new FirstWordFunction(contributions.getTypeConfiguration())<br>        );<br>        <br>        // Register calculate_distance function<br>        contributions.getFunctionRegistry().register(<br>            &quot;calculate_distance&quot;,<br>            new CalculateDistanceFunction(contributions.getTypeConfiguration())<br>        );<br>    }<br>}</pre><h3>4. ServiceLoader Configuration</h3><p>Create the ServiceLoader configuration file:</p><pre># File: src/main/resources/META-INF/services/org.hibernate.boot.model.FunctionContributor<br>com.example.hibernate.functions.CustomFunctionContributor</pre><p>This file is what enables Hibernate to discover our custom functions automatically through the ServiceLoader mechanism.</p><h3>5. Using the Functions in Your Repository</h3><p>Now you can use these functions in your JPA repositories:</p><pre>@Entity<br>@Table(name = &quot;locations&quot;)<br>public class Location {<br>    @Id<br>    private Long id;<br>    private String name;<br>    private Point coordinates;<br>    // getters and setters<br>}<br><br>@Repository<br>public interface LocationRepository extends JpaRepository&lt;Location, Long&gt; {<br>    <br>    @Query(&quot;&quot;&quot;<br>        SELECT new com.example.dto.LocationDTO(<br>            l.id,<br>            first_word(l.name),<br>            calculate_distance(l.coordinates, :referencePoint)<br>        )<br>        FROM Location l<br>        WHERE calculate_distance(l.coordinates, :referencePoint) &lt;= :maxDistance<br>    &quot;&quot;&quot;)<br>    List&lt;LocationDTO&gt; findNearbyLocations(<br>        @Param(&quot;referencePoint&quot;) Point referencePoint,<br>        @Param(&quot;maxDistance&quot;) double maxDistance<br>    );<br>}</pre><h3>Understanding the Implementation Details</h3><h3>Function Descriptor Classes</h3><p>Each function descriptor is responsible for:</p><ol><li><strong>Function Configuration</strong>:</li></ol><ul><li>Defining the function name</li><li>Specifying the function kind (NORMAL in our case)</li><li>Setting up argument validation</li><li>Configuring return type</li></ul><ol><li><strong>SQL Generation</strong>:</li></ol><ul><li>The renderer method handles the SQL generation</li><li>Parameters are properly rendered using the translator</li><li>Type casting is applied where necessary</li></ul><h3>Render Method Implementation</h3><p>The render method follows a specific pattern:</p><ol><li>Uses a private renderer method for SQL generation</li><li>Implements the non-deprecated render method signature</li><li>Handles argument translation and SQL generation</li><li>Manages parameter type casting when needed</li></ol><h3>Best Practices</h3><p><strong>Function Organization</strong></p><ul><li>Keep functions in separate classes</li><li>Use descriptive naming</li><li>Document parameters and return types</li></ul><p><strong>Error Handling</strong></p><ul><li>Validate arguments properly</li><li>Handle type casting correctly</li><li>Consider null values</li></ul><p><strong>Testing</strong></p><ul><li>Create integration tests</li><li>Test with different parameter types</li><li>Verify SQL generation</li></ul><h3>Conclusion</h3><p>Custom SQL functions in Hibernate 6.5.3 with PostgreSQL 16 provide a powerful way to extend your application’s database capabilities. The FunctionContributor approach, combined with Java’s ServiceLoader mechanism, offers a clean and maintainable way to implement these functions.</p><p>Key takeaways:</p><ul><li>Use separate classes for each function</li><li>Implement proper argument validation</li><li>Handle SQL generation carefully</li><li>Test thoroughly with different scenarios</li></ul><p>Remember that with great power comes great responsibility — use custom functions where they make sense and provide clear value to your application.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f416f88dc274" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>