<?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 Abhishek Anand on Medium]]></title>
        <description><![CDATA[Stories by Abhishek Anand on Medium]]></description>
        <link>https://medium.com/@abhiandy?source=rss-95a68422d1f3------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*QVV0Jd1ZhXVZLlLiCmlNKw.jpeg</url>
            <title>Stories by Abhishek Anand on Medium</title>
            <link>https://medium.com/@abhiandy?source=rss-95a68422d1f3------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 21 Nov 2026 14:19:16 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@abhiandy/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[Demystifying Context Propagation in Spring Web flux with ThreadLocalAccessor, ContextRegistry, MDC…]]></title>
            <link>https://medium.com/javarevisited/demystifying-context-propagation-in-spring-web-flux-with-threadlocalaccessor-contextregistry-mdc-c3740e0b990e?source=rss-95a68422d1f3------2</link>
            <guid isPermaLink="false">https://medium.com/p/c3740e0b990e</guid>
            <category><![CDATA[observability]]></category>
            <category><![CDATA[spring-graphql]]></category>
            <category><![CDATA[spring-boot-3]]></category>
            <category><![CDATA[spring-webflux]]></category>
            <category><![CDATA[mdc]]></category>
            <dc:creator><![CDATA[Abhishek Anand]]></dc:creator>
            <pubDate>Sat, 02 Mar 2024 08:29:52 GMT</pubDate>
            <atom:updated>2024-03-05T04:34:58.442Z</atom:updated>
            <content:encoded><![CDATA[<h3>Custom Context Propagation in Spring Web flux with ThreadLocalAccessor, ContextRegistry, MDC, and GraphQL Interceptors</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*BBrDS95oorDoXeH5" /><figcaption>Photo by <a href="https://unsplash.com/@jacegrandinetti?utm_source=medium&amp;utm_medium=referral">Jace &amp; Afsoon</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>In the intricate world of micro services, seamlessly transporting crucial context information among disparate components is essential. This information serves as a vital digital thread, guaranteeing consistency, traceability, and efficient debugging across the entire system. This blog delves into the core concepts of ThreadLocalAccessor, ContextRegistry, Mapped Diagnostic Context (MDC), and Interceptors within the context of Spring Web flux applications. We’ll explore their roles in context propagation and delve into the rationale behind logging context information.</p><h4><strong>Understanding ThreadLocalAccessor, ContextRegistry, and MDC</strong></h4><p><strong><em>ThreadLocalAccessor</em></strong>: This utility facilitates the association of values with individual threads, ensuring thread safety and enabling access to thread specific data from any part of the code execution thread. It’s particularly valuable in asynchronous programming paradigms like Spring Web flux, where context needs to be preserved across asynchronous operations.</p><p><strong><em>ContextRegistry</em></strong>: This component functions as a central hub for managing and accessing context data throughout an application’s execution. It offers methods for registering, retrieving, and unregistering context objects, streamlining context propagation across diverse application layers. Think of it as a central repository where all context information resides. Services can readily deposit and retrieve context data, ensuring consistent access across the application.</p><p><strong><em>MDC (Mapped Diagnostic Context)</em></strong>: This logging framework extension provides a mechanism for associating key-value pairs with the current thread’s context, allowing logging statements to incorporate this contextual information. This enrichment enhances log readability, troubleshooting, and correlation. Imagine a log statement indicating an error during order processing. By including a correlation ID (stored in MDC) within the log, developers can effortlessly trace the specific order encountering the issue and expedite troubleshooting efforts.</p><h4><strong>The Role of Interceptors: Orchestrating Information Flow</strong></h4><p><strong><em>Spring Web flux Interceptors</em></strong>: These interceptors act as intermediaries within the request processing pipeline, enabling you to intercept requests and responses at various stages, perform custom logic, and modify the request or response objects. In context propagation scenarios, interceptors can be used to capture context information from incoming requests (such as headers) and inject it into the reactor context, ensuring it’s readily accessible throughout subsequent processing steps. Think of interceptors as checkpoints where you can examine incoming requests, extract pertinent context information (like authentication tokens or transaction IDs), and make it readily available for downstream services.</p><p><strong><em>WebGraphQL Interceptors</em></strong>: Specifically designed for Spring Boot GraphQL applications, these interceptors offer a means to intercept incoming GraphQL requests and responses, enabling authentication, authorization, data transformation, and other custom processing tasks. They can also be leveraged to propagate context information between the API Gateway and the backend GraphQL service. GraphQL interceptors play a vital role in securing and enriching GraphQL requests before they reach the backend service, while also offering opportunities to propagate context information from the API Gateway to the service.</p><p><strong>Illustrative Code Example and Explanation: Demystifying the Flow</strong></p><p>In the following example, we will walk through a flow where a GraphQL request is received by a backend service through an API gateway. API gateways typically include a trace ID, request ID, or transaction ID in the header, which is then passed to the backend service. This transaction ID is captured in the interceptor and added to both the Reactor context and MDC. Once the transaction ID is appended in all logs, it becomes much easier to troubleshoot using log analysis tools like Splunk or LogInSight.</p><h4><strong>Dependencies</strong></h4><pre>&lt;!-- Spring Webflux starter --&gt;<br>&lt;dependency&gt;<br>    &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt;<br>    &lt;artifactId&gt;spring-boot-starter-webflux&lt;/artifactId&gt;<br>    &lt;version&gt;3.2.2&lt;/version&gt;<br>&lt;/dependency&gt;<br>&lt;!-- Reactor Core --&gt;<br>&lt;dependency&gt;<br>    &lt;groupId&gt;io.projectreactor&lt;/groupId&gt;<br>    &lt;artifactId&gt;reactor-core&lt;/artifactId&gt;<br>    &lt;version&gt;3.6.2&lt;/version&gt;<br>&lt;/dependency&gt;<br>&lt;!-- Reactor Test --&gt;<br>&lt;dependency&gt;<br>    &lt;groupId&gt;io.projectreactor&lt;/groupId&gt;<br>    &lt;artifactId&gt;reactor-test&lt;/artifactId&gt;<br>    &lt;version&gt;3.6.2&lt;/version&gt;<br>    &lt;scope&gt;test&lt;/scope&gt;<br>&lt;/dependency&gt;<br>&lt;!-- Spring GraphQL starter --&gt;<br>&lt;dependency&gt;<br>    &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt;<br>    &lt;artifactId&gt;spring-boot-starter-graphql&lt;/artifactId&gt;<br>    &lt;version&gt;3.2.2&lt;/version&gt;<br>&lt;/dependency&gt;<br>&lt;!-- Micrometer tracing (Required for observability) --&gt;<br>&lt;dependency&gt;<br>    &lt;groupId&gt;io.micrometer&lt;/groupId&gt;<br>    &lt;artifactId&gt;micrometer-tracing-bridge-brave&lt;/artifactId&gt;<br>    &lt;version&gt;1.2.2&lt;/version&gt;<br>&lt;/dependency&gt;<br>&lt;!-- Spring Boot Actuator (Required for observability) --&gt;<br>&lt;dependency&gt;<br>    &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt;<br>    &lt;artifactId&gt;spring-boot-starter-actuator&lt;/artifactId&gt;<br>    &lt;version&gt;3.2.2&lt;/version&gt;<br>&lt;/dependency&gt;</pre><h4>Main class</h4><pre>@PostConstruct<br>public void init() {<br>    Hooks.enableAutomaticContextPropagation();<br>}</pre><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1f3130c9d5d69f284d908e94bd1ca16b/href">https://medium.com/media/1f3130c9d5d69f284d908e94bd1ca16b/href</a></iframe><h4><strong>Explanation</strong>:</h4><p><em>Main Class</em></p><p>Hooks.enableAutomaticContextPropagation()</p><ul><li>Ensures that tracing context is automatically propagated across threads and asynchronous boundaries within reactive flows.</li><li>This is crucial for maintaining a consistent trace throughout the application, even when execution jumps between threads or involves non-blocking operations.</li><li>Called within a @PostConstruct method to guarantee it&#39;s executed early during application startup before any reactive operations begin.</li></ul><p><em>RequestHeaderInterceptor class</em></p><p>1. <strong>Header Extraction</strong>: The code retrieves the <em>tid</em> header value from the incoming request. This value represents a unique identifier for a specific user session or transaction.</p><p>2. <strong>MDC/Context Population</strong>:</p><p>- If the header exists, the transaction ID (extracted from the header) is stored in both MDC and the Reactor context using the ThreadLocalAccessor registered earlier. This ensures that the ID is accessible throughout the thread’s execution and across asynchronous operations facilitated by Reactor.</p><p>3. <strong>Downstream Processing</strong>:</p><p>- The request, now enriched with the transaction ID in both MDC and Reactor context, is passed to the next interceptor in the chain using chain.next(request). This allows subsequent components to access the ID for various purposes, such as logging, tracing, or correlation.</p><p>4. <strong>Reactor Context Enrichment</strong>:</p><p>- Additionally, the code calls contextWrite(Context.of(TRANSACTION_ID_KEY, tid)) to explicitly add the transaction ID to the Reactor context. This ensures that the ID is readily available within the reactive pipeline facilitated by Spring Web flux, enabling consistent access across asynchronous operations.</p><p><strong>logback.xml</strong></p><p>Adding %X means all the key value pairs present in MDC will be printed.</p><p>To print the value of a particular key in MDC , use %X{key-name}.</p><pre>&lt;pattern&gt;<br>    [%date{&quot;yyyy-MM-dd&#39;T&#39;HH:mm:ss,SSSZ&quot;}]-[%-5level]-[&quot;%thread&quot; %X ]-[%logger{25}]-[%line]-%msg %ex{full}%n<br>&lt;/pattern&gt;</pre><p><strong>Log output</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vlyOTvth8i0XsTga1ofuZw.png" /></figure><p>We can see that <strong>txId</strong> is getting appended in the logs. Since micrometer is present in the class path , Spring Boot automatically enables tracing , hence <strong>traceID</strong> and <strong>spanId</strong> are getting appended in the logs.</p><h4><strong>Why Pass Context Information in Logs?</strong></h4><p>Including context information in logs offers a multitude of benefits:</p><p>- <strong><em>Enhanced Debugging</em></strong>: Contextual information, like transaction IDs or user IDs, provides valuable clues when debugging issues. By correlating logs with specific transactions or users, developers can swiftly pinpoint the root cause of problems.</p><p>- <strong><em>Improved Auditing and Monitoring</em></strong>: Context-rich logs empower detailed activity tracking and auditing. By incorporating user IDs, timestamps, and identifiers for specific requests or operations, organisations can gain deeper insights into system behaviour and user interactions.</p><p>- <strong><em>Streamlined Troubleshooting</em></strong>: Imagine encountering an error in a complex micro services architecture. Contextual information in logs acts as a breadcrumb trail, guiding developers through the system’s execution flow, pinpointing the point of failure, and facilitating faster resolution.</p><h4><strong>Conclusion</strong></h4><p>Effectively harnessing ThreadLocalAccessor, ContextRegistry, MDC, Reactor Context, and GraphQL Interceptors empowers seamless context propagation within Spring Web flux and GraphQL applications. This collaborative effort fosters efficient information flow, enhances debugging capabilities, and bolsters overall application operability. By incorporating context into logs, developers gain valuable insights and expedite troubleshooting efforts, ensuring a robust and maintainable system.</p><p><strong>References :</strong></p><p><a href="https://spring.io/blog/2023/03/30/context-propagation-with-project-reactor-3-unified-bridging-between-reactive">https://spring.io/blog/2023/03/30/context-propagation-with-project-reactor-3-unified-bridging-between-reactive</a> <br><a href="https://micrometer.io/docs/contextPropagation">https://micrometer.io/docs/contextPropagation</a></p><p>If you liked the article please take a minute to offer me a clap 👏 or even buy me a coffee <a href="https://www.buymeacoffee.com/abhiandy">https://www.buymeacoffee.com/abhiandy</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c3740e0b990e" width="1" height="1" alt=""><hr><p><a href="https://medium.com/javarevisited/demystifying-context-propagation-in-spring-web-flux-with-threadlocalaccessor-contextregistry-mdc-c3740e0b990e">Demystifying Context Propagation in Spring Web flux with ThreadLocalAccessor, ContextRegistry, MDC…</a> was originally published in <a href="https://medium.com/javarevisited">Javarevisited</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Optimising Performance with GraalVM: Running Spring Boot Native Image on Kubernetes]]></title>
            <link>https://medium.com/codex/optimising-performance-with-graalvm-running-spring-boot-native-image-on-kubernetes-b20942726530?source=rss-95a68422d1f3------2</link>
            <guid isPermaLink="false">https://medium.com/p/b20942726530</guid>
            <category><![CDATA[graalvm]]></category>
            <category><![CDATA[spring-boot]]></category>
            <category><![CDATA[spring-boot-graalvm]]></category>
            <category><![CDATA[docker]]></category>
            <category><![CDATA[java]]></category>
            <dc:creator><![CDATA[Abhishek Anand]]></dc:creator>
            <pubDate>Sun, 19 Feb 2023 04:47:47 GMT</pubDate>
            <atom:updated>2023-02-22T20:08:31.754Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*KH3MvuZHc7-gphuN" /><figcaption>Photo by <a href="https://growtika.com/">Growtika</a></figcaption></figure><p>In the previous <a href="https://medium.com/codex/optimising-performance-with-graalvm-a-guide-to-migrating-a-spring-boot-project-to-native-image-fbb2dcf5d405">article</a>, I explained how to migrate an existing Spring Boot application to use GraalVM native image, which can offer faster startup times and lower memory usage. In this article, we’ll take the next step and explore how to deploy the GraalVM built native executable on Kubernetes. By using Kubernetes, you can easily manage and scale your application, and take advantage of the platform’s built-in features like load balancing and auto-scaling. We’ll walk through the steps for creating a Docker image using a Dockerfile, pushing the image to a container registry, creating a Kubernetes deployment file, and exposing the application to the outside world.</p><h3>Creating Dockerfile</h3><pre>#Use GraalVM Maven base image <br>FROM vegardit/graalvm-maven:22.3.1-java17<br>COPY src /home/app/src<br>COPY pom.xml /home/app<br>#Build a native executable<br>RUN mvn -f /home/app/pom.xml -Pnative native:compile<br>WORKDIR /home/app/target<br>#Expose port on which Spring Boot app will run<br>EXPOSE 9092<br>#Switch to non root user<br>USER 1001<br>#Entrypoint command present in Kubernetes deployment<br><br></pre><ol><li><strong>FROM</strong>: This step specifies the base image to use, which is vegardit/graalvm-maven:22.3.1-java17. This means that the Docker image will be built on top of the GraalVM Maven base image.I have used this <a href="https://github.com/vegardit/docker-graalvm-maven">image</a> as it contains Maven pre-installed with GraalVM.</li><li><strong>COPY</strong>: This step copies the source code of the Spring Boot application to the /home/app/src directory in the Docker image, and the pom.xml file to the /home/app directory.</li><li><strong>RUN</strong>: This step uses the mvn command to build a native executable for the Spring Boot application, by specifying the Maven project file using the -f option and the native profile using the -P option. The native:compile command tells Maven to compile the application to a native executable.</li><li><strong>WORKDIR</strong>: This step sets the working directory to /home/app/target.</li><li><strong>EXPOSE</strong>: This step exposes the port 9092 on which the Spring Boot application will run. This means that when the Docker container is run, this port will be available for other containers or for external clients to access the application.</li><li><strong>USER</strong>: This step sets the user ID to 1001, which is a non-root user. This is a best practice for security reasons, as running an application as a non-root user can reduce the risk of security vulnerabilities.</li><li><strong>ENTRYPOINT</strong>: This step is not present in this Dockerfile, but it is mentioned in the description as being present in the Kubernetes deployment. The entrypoint is the command that is executed when the Docker container is run. In this case, it would be the command to start the Spring Boot application.</li></ol><h3>Running the application on Kubernetes</h3><p>Build the Docker image using the Dockerfile. You can do this by running the following command in the same directory as the Dockerfile:</p><pre>docker build -t your-image-name:version .</pre><p>Push the Docker image to a container registry. This can be a public registry like Docker Hub or a private registry that you have set up for your organization. Make sure to authenticate with the registry before pushing the image.</p><pre>docker push your-image-name</pre><p>Create a Kubernetes deployment file that specifies the Docker image to use, the number of replicas to create, and any other configuration for the deployment. Here’s an example of a deployment file:</p><pre>apiVersion: apps/v1<br>kind: Deployment<br>metadata:<br>  name: your-deployment-name<br>spec:<br>  replicas: 1<br>  selector:<br>    matchLabels:<br>      app: your-app-name<br>  template:<br>    metadata:<br>      labels:<br>        app: your-app-name<br>    spec:<br>      containers:<br>      - name: your-container-name<br>        image: your-image-name<br>        command: [&quot;./your-executable-name&quot;,&quot;-Djavax.net.ssl.trustStore=/opt/certs/truststore.jks&quot;,&quot;-Djavax.net.ssl.trustStorePassword=changeit&quot;]<br>        ports:<br>        - containerPort: 9092</pre><p>The Entrypoint command is provided in the command key which basically runs the executable and additionally passes arguments to load a custom trust store and supplies the password of the trust store.</p><p>You can also add your poperties on ConfigMap and application passwords on Secrets.</p><p>Apply the deployment file to your Kubernetes cluster using the kubectl apply command:</p><pre>kubectl apply -f your-deployment-file.yaml</pre><p>Verify that the deployment and pod have been created using the kubectl command:</p><pre>kubectl get deployments<br>kubectl get pods</pre><p>To expose the application to the outside world, create a Kubernetes Service using the kubectl expose command:</p><pre>kubectl expose deployment your-deployment-name --type=LoadBalancer --port=80 --target-port=9092</pre><p>If you liked the article please take a minute to offer me a clap 👏 or even buy me a coffee <a href="https://www.buymeacoffee.com/abhiandy">https://www.buymeacoffee.com/abhiandy</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b20942726530" width="1" height="1" alt=""><hr><p><a href="https://medium.com/codex/optimising-performance-with-graalvm-running-spring-boot-native-image-on-kubernetes-b20942726530">Optimising Performance with GraalVM: Running Spring Boot Native Image on Kubernetes</a> was originally published in <a href="https://medium.com/codex">CodeX</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Optimising Performance with GraalVM: A Guide to Migrating a Spring Boot Project to Native Image]]></title>
            <link>https://medium.com/codex/optimising-performance-with-graalvm-a-guide-to-migrating-a-spring-boot-project-to-native-image-fbb2dcf5d405?source=rss-95a68422d1f3------2</link>
            <guid isPermaLink="false">https://medium.com/p/fbb2dcf5d405</guid>
            <category><![CDATA[native-app]]></category>
            <category><![CDATA[spring-boot]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[graalvm]]></category>
            <category><![CDATA[spring]]></category>
            <dc:creator><![CDATA[Abhishek Anand]]></dc:creator>
            <pubDate>Sat, 11 Feb 2023 04:59:43 GMT</pubDate>
            <atom:updated>2023-02-19T04:48:54.276Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tSlMpxE34kovQU2-bVxeQA.png" /></figure><p>Spring Boot and GraalVM are two popular technologies in the Java world, and the combination of both has created a lot of buzz lately. GraalVM enables you to create native images, which are executable files that run like any other binary. They are known for their fast startup time and low memory footprint.</p><p>If you are using Spring Boot 3, creating native images is now possible out of the box. In this article, I’ll walk you through the process of converting one of my micro-services into a native image using Spring Boot and GraalVM.</p><h3>Existing Project</h3><p>Before we dive into the conversion process, let’s take a quick look at my project. This micro-service is based on Spring Boot 2.7.6 and Java 17. It connects to Active Directory through the Spring LDAP starter, uses Spring Data Redis for connecting to Redis Sentinel, and also connects to a MySQL database using Spring Data JPA.</p><h4>Old pom.xml</h4><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4d072c549d8971aeb6faf73bd98c6610/href">https://medium.com/media/4d072c549d8971aeb6faf73bd98c6610/href</a></iframe><p>Upgrading to Spring Boot 3 was a straightforward process. I simply had to upgrade the Spring Boot starter to version 3.0.1 and the Spring Cloud to version 2022.0.0. Also replace all javax.* packages with jakarta.* packages. Follow this <a href="https://github.com/spring-projects/spring-boot/wiki/Spring-Boot-3.0-Migration-Guide">article</a> to prepare for migration.</p><h3>Creating native image</h3><p>First of all , we need to have GraalVM JDK installed on our machine.</p><p>SDKMAN is a tool for managing parallel versions of software development kits, including GraalVM. With SDKMAN, you can easily install, switch between different versions, and manage GraalVM installations on your system.</p><p>Before installing GraalVM, you must have SDKMAN <a href="https://www.baeldung.com/java-sdkman-intro">installed</a> on your system.</p><p>To install GraalVM using SDKMAN, follow these steps:</p><ol><li>Open a terminal window on your Mac OS system.</li><li>Run the following command to list the available versions of GraalVM</li></ol><pre>sdk list java</pre><p>You will see a list of available versions of GraalVM. Select the version you want to install by running the following command, replacing “version” with the version number:</p><pre>sdk install java version</pre><p>Wait for the installation process to complete.</p><p>To verify the installation, run the following command:</p><pre>java -version</pre><p>You should see the version of GraalVM you just installed.</p><p>Setting up GraalVM as the Default Java Version To set GraalVM as the default Java version for your system, run the following command:</p><pre>sdk default java version</pre><p>Replace “version” with the version number of GraalVM that you installed.</p><p>Next, we need to add the GraalVM native plugin to our build. This will enable us to create a native executable. The exact process of adding the plugin depends on the build tool you are using. For example, if you are using Maven, you will need to add the following to your pom.xml file:</p><pre>&lt;plugin&gt;<br>    &lt;groupId&gt;org.graalvm.buildtools&lt;/groupId&gt;<br>    &lt;artifactId&gt;native-maven-plugin&lt;/artifactId&gt;<br>&lt;/plugin&gt;</pre><p>The spring-boot-starter-parent declares a native profile that configures the executions that need to run in order to create a native image. You can activate profiles using the -P flag on the command line.</p><p>To build the image, you can run the native:compile goal with the native profile active:</p><pre>./mvnw -Pnative native:compile</pre><p>This will create an executable inside the target directory. You can run it like</p><pre>./target/&lt;native-executable&gt;</pre><h3>Challenges :</h3><p>GraalVM’s static code analysis during build time can result in errors like ClassNotFound, MethodNotFound, and ResourceNotFound. To overcome these challenges, hints need to be provided to let GraalVM know about the dynamic elements of the code. To achieve this, I declared a static inner class ‘MyRuntimeHints’ within the main class.</p><pre>@SpringBootApplication<br>@ImportRuntimeHints(LdapServiceApplication.MyRuntimeHints.class)<br>public class LdapServiceApplication {<br><br> public static void main(String[] args) {<br>  SpringApplication.run(LdapServiceApplication.class, args);<br> }<br><br> @Bean<br> public RestTemplate restTemplate() {<br>  return new RestTemplate();<br> }<br><br> @PostConstruct<br> void postConstruct() {<br>  System.setProperty(&quot;javax.net.ssl.trustStore&quot;, System.getProperty(&quot;javax.net.ssl.trustStore&quot;));<br>  System.setProperty(&quot;javax.net.ssl.trustStorePassword&quot;, System.getProperty(&quot;javax.net.ssl.trustStorePassword&quot;));<br> }<br><br> static class MyRuntimeHints implements RuntimeHintsRegistrar {<br><br>  @Override<br>  public void registerHints(RuntimeHints hints, ClassLoader classLoader) {<br>   // Register serialization<br>   hints.serialization().registerType(HashMap.class).registerType(LinkedList.class);<br>   hints.reflection().registerType(TypeReference.of(&quot;javax.net.ssl.SSLSocketFactory&quot;),<br>     builder -&gt; builder.withMembers(MemberCategory.INVOKE_PUBLIC_METHODS));<br>   hints.resources().registerPattern(&quot;db/migration/*.sql&quot;);<br>  }<br><br></pre><p>The class contains hints to register the HashMap and LinkedList class for deserialisation, which are used when fetching cached data from Redis. It also contains a hint to register the public methods of the SSLSocketFactory class, which I am using for a custom truststore to store CA certificates for the corporate AD server. The third hint is to let GraalVM know the location of my flyway scripts.</p><p>To import the hints, I used the annotation @ImportRuntimeHints(LdapServiceApplication.MyRuntimeHints.class). I also set the system property for dynamically loading the custom truststore and associated password in the PostConstruct method.</p><p>However, I had to comment out the dependencies related to Spring Cloud Kubernetes as it didn’t support AOT at the time of writing this article.</p><p>After adding these modifications, I built the native executable again and it worked smoothly, reducing the startup time by 80%. <strong><em>Woah !!</em></strong></p><pre>./target/ldap-service -Djavax.net.ssl.trustStore=/Users/abhi-codes/Downloads/truststore.jks -Djavax.net.ssl.trustStorePassword=changeit</pre><p>Instead of building image and then running it to test your changes every single time, you can enable AOT processing like below. Refer <a href="https://docs.spring.io/spring-boot/docs/current/reference/html/native-image.html#native-image.testing.with-the-jvm">https://docs.spring.io/spring-boot/docs/current/reference/html/native-image.html#native-image.testing.with-the-jvm</a> for more details.</p><pre>$ java -Dspring.aot.enabled=true -jar ldap-service.jar</pre><p>In conclusion, converting a Spring Boot micro-service to a native image using GraalVM is a simple process that can bring significant performance benefits. With the built-in support in Spring Boot 3, it’s now easier than ever to create native images for your applications.</p><p>In the <a href="https://abhiandy.medium.com/optimising-performance-with-graalvm-running-spring-boot-native-image-on-kubernetes-b20942726530">next article</a> , I will walk you though how to build a native image using Dockerfile and deploy the docker image onto Kubernetes.</p><p>If you liked the article please take a minute to offer me a clap 👏 or even buy me a coffee <a href="https://www.buymeacoffee.com/abhiandy">https://www.buymeacoffee.com/abhiandy</a></p><h4>References :</h4><p><a href="https://docs.spring.io/spring-boot/docs/current/reference/html/native-image.html#native-image.testing.with-the-jvm">GraalVM Native Image Support</a></p><p><a href="https://www.baeldung.com/spring-native-intro">https://www.baeldung.com/spring-native-intro</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fbb2dcf5d405" width="1" height="1" alt=""><hr><p><a href="https://medium.com/codex/optimising-performance-with-graalvm-a-guide-to-migrating-a-spring-boot-project-to-native-image-fbb2dcf5d405">Optimising Performance with GraalVM: A Guide to Migrating a Spring Boot Project to Native Image</a> was originally published in <a href="https://medium.com/codex">CodeX</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Caching with Spring Boot 3, Lettuce, and Redis Sentinel]]></title>
            <link>https://medium.com/javarevisited/caching-with-spring-boot-3-lettuce-and-redis-sentinel-5f6fab7e58f8?source=rss-95a68422d1f3------2</link>
            <guid isPermaLink="false">https://medium.com/p/5f6fab7e58f8</guid>
            <category><![CDATA[spring-boot-3]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[spring-boot]]></category>
            <category><![CDATA[redis-sentinel]]></category>
            <category><![CDATA[redis]]></category>
            <dc:creator><![CDATA[Abhishek Anand]]></dc:creator>
            <pubDate>Tue, 24 Jan 2023 06:41:56 GMT</pubDate>
            <atom:updated>2023-01-25T15:48:32.704Z</atom:updated>
            <content:encoded><![CDATA[<figure><a href="https://javarevisited.blogspot.com/2022/03/spring-boot-redis-example-in-java.html"><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BPaJkTpUnhUTOqcOXiw0XQ.png" /></a><figcaption>Caching with Spring Boot 3, Lettuce, and Redis Sentinel</figcaption></figure><p>In this tutorial, I will walk you through how to connect to Redis Sentinel from Spring Boot and use it for caching.</p><h3>What is Redis Sentinel?</h3><p>Redis Sentinel is the high-availability solution offered by <a href="https://medium.com/javarevisited/top-5-courses-to-learn-redis-for-beginners-best-of-lot-720b8b381fc8">Redis</a>, In case of a failure in your Redis cluster, Sentinel will automatically detect the point of failure and bring the cluster back to stable mode without any human intervention. In other words, Redis Sentinel is a system that can resist Redis deployment without human intervention.</p><figure><a href="https://javarevisited.blogspot.com/2022/02/top-5-courses-to-learn-redis.html"><img alt="" src="https://cdn-images-1.medium.com/max/855/1*hbQi_MlzpUv2Eh8oyRbVcA.png" /></a><figcaption>Redis Sentinel setup</figcaption></figure><h3>Dependencies</h3><p>First, let&#39;s add the below starters to make our life easier.</p><pre>&lt;dependency&gt;<br>   &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt;<br>   &lt;artifactId&gt;spring-boot-starter-data-redis&lt;/artifactId&gt;<br>  &lt;/dependency&gt;<br>  &lt;dependency&gt;<br>   &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt;<br>   &lt;artifactId&gt;spring-boot-starter-cache&lt;/artifactId&gt;<br>  &lt;/dependency&gt;</pre><ol><li>spring-boot-starter-data-redis : It is a Starter for using Redis key-value data store with Spring Data Redis and the Lettuce client</li><li>spring-boot-starter-cache : Starter for <a href="https://medium.com/javarevisited/25-spring-framework-interview-questions-for-1-to-3-years-experienced-java-programmers-567f268ed897">Spring Framework’s</a> caching support, it provides super handy annotations for working with any caching provider.</li></ol><h3>Connecting to Redis Sentinel from Spring Boot 3</h3><p>Now, we are going to create a connection to “Redis Sentinel” with the help of the below configuration class. As I told you before, we are going to use Lettuce to connect to Redis. We are going to create a new instance of RedisSentinelConfiguration class with the help of RedisProperties class and use it in the constructor of LettuceConnectionFactory.</p><p><strong>application.properties</strong></p><pre>spring.data.redis.port=26379<br>spring.data.redis.password=<br>spring.data.redis.sentinel.master=mymaster<br>spring.data.redis.sentinel.nodes=localhost<br>spring.cache.type=redis<br>spring.cache.redis.cache-null-values=false<br>spring.cache.redis.time-to-live=300000<br>spring.data.redis.timeout=600ms</pre><p><strong>RedisConfig.java</strong></p><pre>package com.medium.ldapservice.config;<br><br>import java.time.Duration;<br><br>import org.springframework.beans.factory.annotation.Value;<br>import org.springframework.boot.autoconfigure.data.redis.RedisProperties;<br>import org.springframework.cache.Cache;<br>import org.springframework.cache.annotation.CachingConfigurer;<br>import org.springframework.cache.annotation.EnableCaching;<br>import org.springframework.cache.interceptor.CacheErrorHandler;<br>import org.springframework.context.annotation.Bean;<br>import org.springframework.context.annotation.Configuration;<br>import org.springframework.data.redis.cache.RedisCacheConfiguration;<br>import org.springframework.data.redis.cache.RedisCacheManager;<br>import org.springframework.data.redis.connection.RedisPassword;<br>import org.springframework.data.redis.connection.RedisSentinelConfiguration;<br>import org.springframework.data.redis.connection.lettuce.LettuceClientConfiguration;<br>import org.springframework.data.redis.connection.lettuce.LettuceConnectionFactory;<br>import org.springframework.data.redis.core.RedisTemplate;<br>import org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer;<br>import org.springframework.data.redis.serializer.GenericToStringSerializer;<br>import org.springframework.data.redis.serializer.JdkSerializationRedisSerializer;<br>import org.springframework.data.redis.serializer.RedisSerializationContext.SerializationPair;<br>import org.springframework.data.redis.serializer.StringRedisSerializer;<br><br>import io.lettuce.core.ReadFrom;<br>import lombok.RequiredArgsConstructor;<br>import lombok.extern.slf4j.Slf4j;<br><br>@Slf4j<br>@Configuration<br>@EnableCaching<br>@RequiredArgsConstructor<br>public class RedisConfig implements CachingConfigurer {<br><br> @Value(&quot;${spring.cache.redis.time-to-live}&quot;)<br> private long redisTimeToLive;<br><br> @Value(&quot;${spring.data.redis.timeout}&quot;)<br> private Duration redisCommandTimeout;<br><br> private final RedisProperties redisProperties;<br><br> @Bean<br> protected LettuceConnectionFactory redisConnectionFactory() {<br>  RedisSentinelConfiguration sentinelConfig = new RedisSentinelConfiguration()<br>    .master(redisProperties.getSentinel().getMaster());<br>  redisProperties.getSentinel().getNodes().forEach(s -&gt; sentinelConfig.sentinel(s, redisProperties.getPort()));<br>  sentinelConfig.setPassword(RedisPassword.of(redisProperties.getPassword()));<br><br>  LettuceClientConfiguration clientConfig = LettuceClientConfiguration.builder()<br>    .commandTimeout(redisCommandTimeout).readFrom(ReadFrom.REPLICA_PREFERRED).build();<br>  return new LettuceConnectionFactory(sentinelConfig, clientConfig);<br> }<br><br> @Bean<br> public RedisTemplate&lt;String, Object&gt; redisTemplate() {<br>  final RedisTemplate&lt;String, Object&gt; redisTemplate = new RedisTemplate&lt;&gt;();<br>  redisTemplate.setKeySerializer(new StringRedisSerializer());<br>  redisTemplate.setHashKeySerializer(new GenericToStringSerializer&lt;&gt;(Object.class));<br>  redisTemplate.setHashValueSerializer(new JdkSerializationRedisSerializer());<br>  redisTemplate.setValueSerializer(new JdkSerializationRedisSerializer());<br>  redisTemplate.setConnectionFactory(redisConnectionFactory());<br>  return redisTemplate;<br> }<br><br> @Override<br> @Bean<br> public RedisCacheManager cacheManager() {<br>  return RedisCacheManager.builder(this.redisConnectionFactory()).cacheDefaults(this.cacheConfiguration())<br>    .build();<br> }<br><br> @Bean<br> public RedisCacheConfiguration cacheConfiguration() {<br>  return RedisCacheConfiguration.defaultCacheConfig().entryTtl(Duration.ofMinutes(redisTimeToLive))<br>    .disableCachingNullValues()<br>    .serializeValuesWith(SerializationPair.fromSerializer(new GenericJackson2JsonRedisSerializer()));<br> }<br><br> @Override<br> public CacheErrorHandler errorHandler() {<br>  return new CacheErrorHandler() {<br>   @Override<br>   public void handleCacheGetError(RuntimeException exception, Cache cache, Object key) {<br>    log.info(&quot;Failure getting from cache: &quot; + cache.getName() + &quot;, exception: &quot; + exception.toString());<br>   }<br><br>   @Override<br>   public void handleCachePutError(RuntimeException exception, Cache cache, Object key, Object value) {<br>    log.info(&quot;Failure putting into cache: &quot; + cache.getName() + &quot;, exception: &quot; + exception.toString());<br>   }<br><br>   @Override<br>   public void handleCacheEvictError(RuntimeException exception, Cache cache, Object key) {<br>    log.info(&quot;Failure evicting from cache: &quot; + cache.getName() + &quot;, exception: &quot; + exception.toString());<br>   }<br><br>   @Override<br>   public void handleCacheClearError(RuntimeException exception, Cache cache) {<br>    log.info(&quot;Failure clearing cache: &quot; + cache.getName() + &quot;, exception: &quot; + exception.toString());<br>   }<br>  };<br> }<br><br>}</pre><p>The <strong>RedisProperties</strong> we defined is a @ConfigrationProperties class. It maps the fields in its own class with the spring.data.redis prefix which we defined in application.properties and presents it to us. We have defined our connection configuration with the fields in the RedisProperties.</p><p>redisConnectionFactory() -&gt; With the help of RedisSentinelConfiguration class, we set up RedisConnection via RedisConnectionFactory. Then we create a LettuceClientConfiguration where we set a custom command timeout(default is 60s) and preference for reading from slaves instead of master.</p><p>cacheManager() -&gt; We initialize the cache Manager to the Redis Sentinel connection created above and also supply the configuration for the cache with the below cache configuration bean. This helps with the @Cacheable annotation.</p><p>cacheConfiguration() -&gt;The behavior of RedisCache created with RedisCacheManager is defined with RedisCacheConfiguration. The configuration lets you set key expiration times, prefixes, and RedisSerializer implementations for converting to and from the binary storage format.</p><p>errorHandler() -&gt; We define a custom error handler to handle any exceptions occurred during any Redis command execution. This helps to connect to the actual source of data instead of throwing an exception if the Redis command execution failed.</p><p>redisTemplate() -&gt; It is used to define the way how serialization/deserialization of keys and values will be done when stored and fetched from the Redis cache.</p><h3>How to use it?</h3><p>We can simply interact with Redis Cache using the @Cacheable annotation. Annotate this on top of service methods like below.</p><pre> @Cacheable(value = &quot;user&quot;, key = &quot;#username&quot;,unless=&quot;#result.size()==0&quot;)<br> @Override<br> public List&lt;Map&lt;String, Object&gt;&gt; getAttributes(String username) {<br>   //Return from DB<br>  }</pre><p>This will create a key user:&lt;username&gt; and store the value returned from the function in the cache only if the returned result size is greater than zero. Empty values will not create an entry in the Redis cache.</p><h3>Setting up a local Redis Sentinel cluster</h3><p>Install Docker on your machine and start it. Create the below file.</p><p><strong>docker-compose.yml</strong></p><pre>version: &#39;2&#39;<br><br>networks:<br>  app-tier:<br>    driver: bridge<br><br>services:<br>  redis:<br>    image: &#39;bitnami/redis:latest&#39;<br>    environment:<br>      - ALLOW_EMPTY_PASSWORD=yes<br>    ports:<br>      - &#39;6379:6379&#39;<br>    networks:<br>      - app-tier<br>  redis-sentinel:<br>    image: &#39;bitnami/redis-sentinel:latest&#39;<br>    environment:<br>      - REDIS_MASTER_HOST=localhost<br>      - REDIS_SENTINEL_RESOLVE_HOSTNAMES=yes<br>    ports:<br>      - &#39;26379:26379&#39;<br>    networks:<br>      - app-tier</pre><p><strong>Bring up the Redis Sentinel using the below command</strong></p><p>docker-compose up -d</p><p><strong>Connect to Redis Sentinel from the command line</strong></p><p>redis-cli -h localhost -p 26379</p><p>You can run Sentinel commands now like to find the master IP address.</p><p><strong>Connect to the Redis node from the command line</strong></p><p>redis-cli -h localhost -p 6379</p><p>You can run the below command to see the list of keys stored in the Redis Node</p><p>keys *</p><p><em>If you liked the article please take a minute to offer me a clap 👏 (you can clap multiple times), follow me, or even buy me a ☕️</em><a href="https://www.buymeacoffee.com/abhiandy">https://www.buymeacoffee.com/abhiandy</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5f6fab7e58f8" width="1" height="1" alt=""><hr><p><a href="https://medium.com/javarevisited/caching-with-spring-boot-3-lettuce-and-redis-sentinel-5f6fab7e58f8">Caching with Spring Boot 3, Lettuce, and Redis Sentinel</a> was originally published in <a href="https://medium.com/javarevisited">Javarevisited</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Create custom annotation in Spring Boot using AOP to check roles]]></title>
            <link>https://medium.com/codex/create-custom-annotation-in-spring-boot-using-aop-to-check-roles-37583f2e81e2?source=rss-95a68422d1f3------2</link>
            <guid isPermaLink="false">https://medium.com/p/37583f2e81e2</guid>
            <category><![CDATA[annotations]]></category>
            <category><![CDATA[spring-boot]]></category>
            <category><![CDATA[aop]]></category>
            <category><![CDATA[java]]></category>
            <dc:creator><![CDATA[Abhishek Anand]]></dc:creator>
            <pubDate>Sat, 14 Jan 2023 05:33:05 GMT</pubDate>
            <atom:updated>2023-01-18T21:29:03.356Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*ZlKmHvpSWoj6JH8h" /><figcaption>Photo by <a href="https://unsplash.com/@pankajpatel?utm_source=medium&amp;utm_medium=referral">Pankaj Patel</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Mosty all projects now are developed using a micro-service architecture where we use Rest Controllers to create the APIs. And the APIs need to be secured by adding a check to see if the user has appropriate permissions/roles to perform the API. In this article, we are going to look at how we can use a custom annotation and Spring AOP to make things easier.</p><h3>Create a custom annotation</h3><p>First, we create a custom annotation wherein we define the target type to be the method, this means that this annotation can be applied only to methods. The annotation expects a String array to be passed; this array will contain the roles which will be allowed to invoke the REST controller method.</p><pre>package com.xxx.pcqcommons.annotation;<br><br>import java.lang.annotation.ElementType;<br>import java.lang.annotation.Retention;<br>import java.lang.annotation.RetentionPolicy;<br>import java.lang.annotation.Target;<br><br>@Target(ElementType.METHOD)<br>@Retention(RetentionPolicy.RUNTIME)<br>public @interface RolesAllowed {<br><br>    String[] value();<br>}</pre><h3>Use Spring AOP to do the magic</h3><p>We create a custom aspect that will do the actual validation of the roles of the caller.</p><p>As we see in the below code, we are using @Before advice and the JoinPoint is on all the methods that contain the above annotation. This ensures that our aspect runs only on methods containing the above annotation and before the method execution begins.</p><p>Next, we write the Advice which needs to be executed on JoinPoint. Here we basically get the roles passed in the annotation and the username from the Request header and check in our database if the user has the roles. If yes, they are able to execute the method else an exception is thrown.</p><pre>@Aspect<br>@Component<br>public class RoleCheckAspect {<br><br> private static final String XREMOTEUSER = &quot;x-remote-user&quot;;<br><br> @Autowired<br> UsersRoleRepository usersRoleRepository;<br><br> @Before(&quot;@annotation(com.xxx.annotation.RolesAllowed)&quot;)<br> public void before(JoinPoint joinPoint) {<br><br>  MethodSignature ms = (MethodSignature) joinPoint.getSignature();<br>  // Get expected Roles from annotation<br>  String[] expectedRoles = ms.getMethod().getAnnotation(RolesAllowed.class).value();<br>  // Get all annotations defined in method signature<br>  Annotation[][] parameterAnnotations = ms.getMethod().getParameterAnnotations();<br>  // Get actual arguments from the method<br>  Object[] args = joinPoint.getArgs();<br><br>  // Get xRemoteUser(username) from Request header<br>  int headerIndex = -1;<br>  boolean found = false;<br>  for (int argIndex = 0; argIndex &lt; parameterAnnotations.length; argIndex++) {<br>   for (Annotation annotation : parameterAnnotations[argIndex]) {<br>    if (!(annotation instanceof RequestHeader))<br>     continue;<br>    RequestHeader requestHeader = (RequestHeader) annotation;<br>    if (XREMOTEUSER.equals(requestHeader.value())) {<br>     headerIndex = argIndex;<br>     found = true;<br>     break;<br>    }<br>   }<br>   if (found)<br>    break;<br>  }<br><br>  // Check if role of xRemoteUser is contained in expectedRoles<br>  if (found) {<br>   if (!usersRoleRepository.findByUsername((String) args[headerIndex]).map(UserRoles::getRoles)<br>     .orElseGet(Collections::emptyList).stream().anyMatch(Arrays.asList(expectedRoles)::contains))<br>    throw new CustomException(ErrorMessage.NO_ACCESS);<br>  } else {<br>   throw new CustomException(ErrorMessage.NO_ACCESS);<br>  }<br> }<br>}</pre><h3>Using the annotation on the controller</h3><p>Pass the roles which should be allowed to execute the method.</p><pre> @GetMapping(&quot;/all&quot;)<br> @ApiOperation(value = &quot;Get all countries&quot;)<br> @RolesAllowed(value={&quot;ROLE_ADMIN&quot;,&quot;ROLE_SUPERADMIN&quot;})<br> public List&lt;Country&gt; getAllCountries(@RequestHeader(required = true, value = &quot;x-remote-user&quot;) String xRemoteUser) {<br>  return cs.getAllCountries();<br> }</pre><p><em>If you liked the article please take a minute to offer me a clap 👏 (you can clap multiple times), follow me, or even buy me a coffee </em><a href="https://www.buymeacoffee.com/abhiandy">https://www.buymeacoffee.com/abhiandy</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=37583f2e81e2" width="1" height="1" alt=""><hr><p><a href="https://medium.com/codex/create-custom-annotation-in-spring-boot-using-aop-to-check-roles-37583f2e81e2">Create custom annotation in Spring Boot using AOP to check roles</a> was originally published in <a href="https://medium.com/codex">CodeX</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Register custom or non-standard SQL functions in Spring Boot JPA or Query DSL]]></title>
            <link>https://medium.com/codex/register-custom-or-non-standard-sql-functions-in-spring-boot-jpa-or-query-dsl-34980fb42cf1?source=rss-95a68422d1f3------2</link>
            <guid isPermaLink="false">https://medium.com/p/34980fb42cf1</guid>
            <category><![CDATA[sql]]></category>
            <category><![CDATA[spring-boot]]></category>
            <category><![CDATA[hibernate]]></category>
            <category><![CDATA[jpa]]></category>
            <dc:creator><![CDATA[Abhishek Anand]]></dc:creator>
            <pubDate>Sun, 20 Nov 2022 08:14:48 GMT</pubDate>
            <atom:updated>2023-01-17T11:16:13.338Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*LqHz5_MOE0eAKGCA" /><figcaption>Photo by <a href="https://unsplash.com/@cdr6934?utm_source=medium&amp;utm_medium=referral">Chris Ried</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>JPA supports most of the standard SQL functions which can be used in writing queries. But how do we use the non-standard or custom DB functions in JPA/Hibernate? Native queries are one way to do that but how to use it if we are writing dynamic queries using Criteria API or Query DSL.</p><h3>Registering the SQL function with JPA and MetadataBuilderContributor</h3><p>Since Hibernate 5.2.18, you can use the MetadataBuilderContributor utility to customize the MetadataBuilder even if you are bootstrapping via JPA.</p><p>The MetadataBuilderContributor interface can be implemented like this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d46814e156b3e09e35aa859d0f0cc69f/href">https://medium.com/media/d46814e156b3e09e35aa859d0f0cc69f/href</a></iframe><p>In the above snippet, I am overriding the contribute method by providing one of the MySQL JSON functions.</p><p>The JSON_CONTAINS() function checks whether one JSON document contains another JSON document.</p><p><strong>JSON_CONTAINS(target_json, candidate_json)</strong></p><p><strong>Parameters</strong></p><p><em>target_json</em>Required. A JSON document.</p><p><em>candidate_json</em>Required. The included JSON document.</p><p>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().</p><p>And provide the custom MetadataBuilderContributor to Hibernate via the <a href="https://vladmihalcea.com/hibernate-sql-function-jpql-criteria-api-query/">hibernate.metadata_builder_contributor</a> configuration property.</p><pre>spring.jpa.properties.hibernate.metadata_builder_contributor=com.abhicodes.customdialect.util.SQLFunctionContributor</pre><h3>Using Custom Function in Query DSL Query</h3><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ad69ba0b5e347e2b10b4c588e1f2c4fb/href">https://medium.com/media/ad69ba0b5e347e2b10b4c588e1f2c4fb/href</a></iframe><p>Since <strong>JSON_CONTAINS</strong>() returns a boolean value, I am using Expressions.booleanTemplate to form the predicate, pass in the custom key, and the two required parameters: target JSON and candidate JSON. Thereafter I pass the predicate to the repository to fetch the values.</p><p>You can find a full working code on <a href="https://github.com/Abhi-Codes/custom-dialect">Github</a>.</p><p><em>If you liked the article please take a minute to offer me a clap 👏 (you can clap multiple times), follow me, or even buy me a coffee </em><a href="https://www.buymeacoffee.com/abhiandy">https://www.buymeacoffee.com/abhiandy</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=34980fb42cf1" width="1" height="1" alt=""><hr><p><a href="https://medium.com/codex/register-custom-or-non-standard-sql-functions-in-spring-boot-jpa-or-query-dsl-34980fb42cf1">Register custom or non-standard SQL functions in Spring Boot JPA or Query DSL</a> was originally published in <a href="https://medium.com/codex">CodeX</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Write production-ready optimized Dockerfile for Spring Boot application]]></title>
            <link>https://medium.com/codex/write-production-ready-optimized-dockerfile-for-spring-boot-application-8fec0906a894?source=rss-95a68422d1f3------2</link>
            <guid isPermaLink="false">https://medium.com/p/8fec0906a894</guid>
            <category><![CDATA[layered]]></category>
            <category><![CDATA[spring-boot]]></category>
            <category><![CDATA[multi-stage-dockerfile]]></category>
            <category><![CDATA[production]]></category>
            <category><![CDATA[jar]]></category>
            <dc:creator><![CDATA[Abhishek Anand]]></dc:creator>
            <pubDate>Sun, 06 Nov 2022 04:59:33 GMT</pubDate>
            <atom:updated>2023-01-17T11:17:40.310Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*DB_MrUJLMmXD7Fmr" /><figcaption>Photo by <a href="https://unsplash.com/@carrier_lost?utm_source=medium&amp;utm_medium=referral">Ian Taylor</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3>Dockerfile</h3><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5fcf2132bb62c39debe7f24854c706ce/href">https://medium.com/media/5fcf2132bb62c39debe7f24854c706ce/href</a></iframe><h3>Stage 1 — Builder</h3><p>I am using Multi-stage Docker build to create the image. In the first stage, I use maven-3.8.3-openjdk-17as my base image and copy the pom.xml and code base to the image. Using the mvn package command, I build an uber jar that contains the package <em>and</em> all its dependencies in one single JAR file.</p><p>This uber jar can easily reach 400MB or more. This means that for every new build, even for the simplest code change in our application:</p><ul><li>A new 400MB layer will be created</li><li>The layer will be uploaded to your OCI registry</li><li>When Kubernetes pulls the latest image to the node that runs the container, the entire 400 MB layer will need to be pulled.</li></ul><p>This will happen on every single code change and rebuild of the image. In reality, only a very small sliver of compiled code has changed. Dockerfile treats each new line as a new layer, so it would make a lot more sense to put the third-party dependencies in their own layer and have our custom code in its own layer. Spring boot provides a way to explode the jar into layers from 2.3 onwards.</p><h3>Layering</h3><p>Instead of <em>running</em> the Spring Boot application, passing the argument -Djarmode=layertools list to the java command will simply list the layers that make sense for the Spring Boot application. In our case, these are:</p><ul><li><strong>Dependencies</strong> — the Spring Boot and other frameworks’ release-based dependencies. These only change when we upgrade to a Spring Boot version or the third-party framework version.</li><li><strong>Spring Boot Loader </strong>— this is the code that loads our Spring Boot app into the JVM to manage the bean lifecycle, among other things. This also rarely changes.</li><li><strong>Snapshot Dependencies</strong> — these dependencies are changing much more often. It’s possible that on each new build it would require us to pull the latest snapshot. As a result, this layer is the closest to our application code.</li><li><strong>Application</strong> — This is our application code from src/main/java (in the case of maven).</li></ul><p>Using Djarmode=layertools extractcommand will extract the layers into the target directory.</p><h3>Stage 2 — Spring Boot Application</h3><p>In the next stage, we use openjdk-17 as the base image and copy the layers one by one from the previous stage to the current stage image. Since each line in Dockerfile creates an individual layer that can be cached, this helps in the next run when there is only code change and no dependency change, meaning Docker can reuse the old cached layers of dependencies. This helps in optimizing the build time.</p><p>Thereafter, I expose the port on which Spring Boot will run and switch to a non-root user. The last line loads the Spring Boot application and runs it.</p><h3>Customizing the layers</h3><p>I had my own set of dependencies that were not part of the dependencies provided by Spring. For example, I had a custom library to connect to a file storage service. It made sense to extract such dependencies into their own layer as well since it changes more often than the Spring dependencies. To do it, I created a custom layers configuration:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/04cab20f5bd671dd71f485f400691352/href">https://medium.com/media/04cab20f5bd671dd71f485f400691352/href</a></iframe><p>Always order the layers in such a way that the least changed layers are in beginning and the more frequently changed layers at the end.</p><p>To apply this configuration in the application, point the spring-boot-maven-plugin to the custom layer configuration:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*k5Gk6mibyd8opwcQv_JgJg.png" /><figcaption>Include custom layers file in Spring Boot maven plugin</figcaption></figure><p><em>If you liked the article please take a minute to offer me a clap 👏 (you can clap multiple times), follow me, or even buy me a coffee </em><a href="https://www.buymeacoffee.com/abhiandy">https://www.buymeacoffee.com/abhiandy</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8fec0906a894" width="1" height="1" alt=""><hr><p><a href="https://medium.com/codex/write-production-ready-optimized-dockerfile-for-spring-boot-application-8fec0906a894">Write production-ready optimized Dockerfile for Spring Boot application</a> was originally published in <a href="https://medium.com/codex">CodeX</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Spring Boot — Create Custom Annotation to validate Request Parameter]]></title>
            <link>https://medium.com/codex/spring-boot-create-custom-annotation-to-validate-request-parameter-dcf483539d90?source=rss-95a68422d1f3------2</link>
            <guid isPermaLink="false">https://medium.com/p/dcf483539d90</guid>
            <category><![CDATA[java]]></category>
            <category><![CDATA[annotations]]></category>
            <category><![CDATA[spring-boot]]></category>
            <category><![CDATA[validator]]></category>
            <category><![CDATA[spring-training]]></category>
            <dc:creator><![CDATA[Abhishek Anand]]></dc:creator>
            <pubDate>Sun, 23 Oct 2022 04:34:01 GMT</pubDate>
            <atom:updated>2023-01-17T11:18:02.943Z</atom:updated>
            <content:encoded><![CDATA[<h3>Spring Boot — Create Custom Annotation to validate Request Parameter</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*41Gx47hmLwo9mdIA" /><figcaption>Photo by <a href="https://unsplash.com/@cbpsc1?utm_source=medium&amp;utm_medium=referral">Clint Patterson</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>While I was working on a Spring Boot Project, I found that custom annotations can be used for validation. The best way to understand how it works as well as how we can use custom annotations for validation is to create simple use cases and try to understand how it works. Here I will be creating a custom annotation to validate the allowed values in any request parameter.</p><p><strong>What is an Annotation?</strong></p><p>“An annotation is nothing but metadata about a field, parameter, method, constructor, type (<em>class/interface/enum</em>), package, and annotation type”.</p><p>Java annotations are a mechanism for adding metadata information to our source code. They’re a powerful part of Java that was added in JDK5. Annotations offer an alternative to the use of XML descriptors and marker interfaces.</p><p>Although we can attach them to packages, classes, interfaces, methods, and fields, annotations by themselves have no effect on the execution of a program.</p><ol><li><strong>Add the spring-boot-starter-validation dependency.</strong></li></ol><p>Validation starter is not included in web starters anymore. The spring-boot-starter-validation is not a transitive dependency of spring-boot-starter-web and spring-boot-starter-webflux anymore.</p><p>Add this dependency for validation work.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/42e0a91c04d3f2447d6200dfbcd605e4/href">https://medium.com/media/42e0a91c04d3f2447d6200dfbcd605e4/href</a></iframe><p>2. <strong>Create a Custom Annotation</strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/36399056ce455036da48e260810b11c1/href">https://medium.com/media/36399056ce455036da48e260810b11c1/href</a></iframe><p>Here, we will add a constraint to validate any Request Param field. Our Validator will have three fields: first is propName which will define any custom property, the second is values which will contain the list of allowed values for the propName and the third is the message which will hold the error message.</p><pre>@Constraint(validatedBy = ValuesAllowed.Validator.class)</pre><p>When validation fails, I return the error message mentioned for the @ValuesAllowed annotation.</p><pre>String message() default &quot;Field value should be from list of &quot;;</pre><p>I am adding validation logic by implementing the interface ConstraintValidator. I initialize the interface variables in the overridden initialize method.</p><p>In the overridden isValid method, I am performing a simple check if the passed value is present in the list of allowed values. If it is not present, throw an error message.</p><p>3. <strong>Add the validation in the controller.</strong></p><p>Here I am adding the annotation on orderBy Request Param. I am passing in a custom property name and list of allowed values for orderBy Request in the annotation.</p><p>Annotate the Controller with @Validated annotation, otherwise the annotation ValuesAllowed will not be triggered at all.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ce3ad9d456210261ac30f560bf22ea0a/href">https://medium.com/media/ce3ad9d456210261ac30f560bf22ea0a/href</a></iframe><p><strong>Note</strong></p><p>The code above returns HTTP 500 if any validation error happens and pollutes logs with an ugly stack trace. To avoid it, we can put an @ExceptionHandler method in the controller body (so it will be scoped only to this controller) and you gain control over HTTP status:</p><pre>@ExceptionHandler(ConstraintViolationException.class)<br>@ResponseStatus(HttpStatus.BAD_REQUEST)<br>String handleConstraintViolationException(ConstraintViolationException e) {<br>    return &quot;Validation error: &quot; + e.getMessage();<br>}</pre><p>… or you can put this method into the separate @ControllerAdvice class and have even more control over this validation like using it across all the controllers or only desired ones.</p><p><em>If you liked the article please take a minute to offer me a clap 👏 (you can clap multiple times), follow me, or even buy me a coffee </em><a href="https://www.buymeacoffee.com/abhiandy">https://www.buymeacoffee.com/abhiandy</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=dcf483539d90" width="1" height="1" alt=""><hr><p><a href="https://medium.com/codex/spring-boot-create-custom-annotation-to-validate-request-parameter-dcf483539d90">Spring Boot — Create Custom Annotation to validate Request Parameter</a> was originally published in <a href="https://medium.com/codex">CodeX</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Add Global parameters in SpringFox Swagger with Spring Boot]]></title>
            <link>https://abhiandy.medium.com/add-global-parameters-in-springfox-swagger-with-spring-boot-39c7ae528322?source=rss-95a68422d1f3------2</link>
            <guid isPermaLink="false">https://medium.com/p/39c7ae528322</guid>
            <category><![CDATA[swagger]]></category>
            <category><![CDATA[swagger-ui]]></category>
            <category><![CDATA[spring-boot]]></category>
            <category><![CDATA[swagger3]]></category>
            <category><![CDATA[java]]></category>
            <dc:creator><![CDATA[Abhishek Anand]]></dc:creator>
            <pubDate>Sun, 09 Oct 2022 06:49:10 GMT</pubDate>
            <atom:updated>2023-01-17T11:18:12.358Z</atom:updated>
            <content:encoded><![CDATA[<figure><a href="https://javarevisited.blogspot.com/2021/04/best-reactive-spring-and-webflux-courses-for-java-developers.html"><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*1ZWITm5S8d2bxryi" /></a><figcaption>Photo by <a href="https://unsplash.com/@cgower?utm_source=medium&amp;utm_medium=referral">Christopher Gower</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>This article is about adding <strong>custom headers</strong> in all Apis <strong>globally</strong> without writing in each API method.</p><p>A complete working code can be found on <a href="https://github.com/Abhi-Codes/springfox-swagger3">GitHub</a>.</p><h3><strong>Why do we need it?</strong></h3><p>There are cases where we need some header value from clients to validate the request.</p><p><em>Example</em> — In our project, we had to pass user and impersonate user info from frontend to backend services. Since these two headers had to be passed in all the API endpoints, they had to be added globally to all Swagger API operations.</p><h3><strong>Dependency</strong></h3><p>Add the springfox dependency.</p><p>The latest version can be downloaded from <a href="https://mvnrepository.com/artifact/io.springfox/springfox-boot-starter">Maven Central</a>.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/77ec3018f6a23e6b46afc9632202111b/href">https://medium.com/media/77ec3018f6a23e6b46afc9632202111b/href</a></iframe><h3><strong>Global Request Parameter</strong></h3><p>The first step would be to create a docket bean as below.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c0bb4a2dfe842375607ea3c5850a8da0/href">https://medium.com/media/c0bb4a2dfe842375607ea3c5850a8da0/href</a></iframe><p>globalRequestParameters <a href="https://springfox.github.io/springfox/docs/snapshot/#springfox-spring-mvc-and-spring-boot">method</a> in the <strong>Docket</strong> <strong>builder</strong> accepts a list of parameters that will be part of every API operation in the generated Swagger specification.</p><p>Parameters can be instantiated using <a href="https://springfox.github.io/springfox/javadoc/current/springfox/documentation/builders/RequestParameterBuilder.html">RequestParameterBuilder</a> , another builder class, which has methods to <strong>accept name, description,type of Parameter , is Required.</strong></p><p>If any specifications need to be added to the parameter, use <a href="https://springfox.github.io/springfox/javadoc/current/springfox/documentation/builders/SimpleParameterSpecificationBuilder.html">SimpleParameterSpecificationBuilder</a>.</p><p><strong>Finally, a simple hello-world controller to test what we just made.</strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/781bd372d289d1eebe47461ad629f7a4/href">https://medium.com/media/781bd372d289d1eebe47461ad629f7a4/href</a></iframe><h3>How the output will look like?</h3><figure><a href="https://www.java67.com/2012/08/spring-interview-questions-answers.html"><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*iqUIajl8lSo20fEBJwbT-g.png" /></a></figure><p><em>If you liked the article please take a minute to offer me a clap 👏 (you can clap multiple times), follow me, or even buy me a coffee </em><a href="https://www.buymeacoffee.com/abhiandy">https://www.buymeacoffee.com/abhiandy</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=39c7ae528322" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Dynamic Query Predicate generation using SpringBoot and QueryDSL]]></title>
            <link>https://medium.com/javarevisited/dynamic-query-predicate-generation-using-springboot-and-querydsl-fdb0d5d3555b?source=rss-95a68422d1f3------2</link>
            <guid isPermaLink="false">https://medium.com/p/fdb0d5d3555b</guid>
            <category><![CDATA[java]]></category>
            <category><![CDATA[spring-boot]]></category>
            <category><![CDATA[querydsl]]></category>
            <category><![CDATA[hibernate]]></category>
            <category><![CDATA[jpa]]></category>
            <dc:creator><![CDATA[Abhishek Anand]]></dc:creator>
            <pubDate>Fri, 30 Sep 2022 08:07:45 GMT</pubDate>
            <atom:updated>2023-01-17T11:18:25.290Z</atom:updated>
            <content:encoded><![CDATA[<h3>Use SpringBoot and QueryDSL to generate production-grade dynamic filters</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*0HNaJHFQnslJAEXo" /><figcaption>Photo by <a href="https://unsplash.com/@austindistel?utm_source=medium&amp;utm_medium=referral">Austin Distel</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>I was tired of writing multiple API endpoints for frontend applications to display filtered information to the users, so came up with a generic solution that works for any table and any database using Spring Boot, QueryDSL, and <a href="https://medium.com/javarevisited/5-best-spring-data-jpa-courses-for-java-developers-45e6438be3c9">JPA</a>. Using this approach, the frontend just needs to invoke one endpoint and pass in the column names, what type of operation they want to perform on that column and the value.</p><p>A complete working code can be found on my <a href="https://github.com/Abhi-Codes/querydsl-dynamic-query">GitHub repo</a>.</p><h3>Dependencies</h3><p>You’ll need to add the following to your pom file.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/df7c6c458ddf4a989a4136044de3384c/href">https://medium.com/media/df7c6c458ddf4a989a4136044de3384c/href</a></iframe><h3>Entities</h3><figure><a href="https://javarevisited.blogspot.com/2021/05/sql-and-database-phone-interview-questions.html"><img alt="" src="https://cdn-images-1.medium.com/max/672/1*LQN54QP-MtNOWt7r9H20AQ.png" /></a><figcaption>ER diagram</figcaption></figure><p>There is a Posts table. A post is associated with a Post Type table using one-to-one mapping. A Post is written by an author and is associated with Users table using many-to-one mapping. Entity mappings can be found <a href="https://github.com/Abhi-Codes/querydsl-dynamic-query/tree/master/src/main/java/com/abhicodes/querydsldynamicquery/entity">here</a>. Once the entities are created, run mvn clean install to generate the Q classes.</p><h3><strong>Repository</strong></h3><p>The QueryDslPredicateExecutor interface exposes some very useful methods for our collection. The one we will be focusing on today is the Iterable&lt;T&gt; findAll(Predicate var1) method.</p><p>Our code today will essentially boil down to allowing our users to create a Predicate such that they can search through the table themselves.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/be281a36d34a3ef65ac773f6b508be05/href">https://medium.com/media/be281a36d34a3ef65ac773f6b508be05/href</a></iframe><h3>Creating the Predicate</h3><p>Now that we have this <a href="https://javarevisited.blogspot.com/2021/10/what-is-spring-data-repository.html">repository</a>, all we really need to do is allow our users to build their own Predicate classes to search for whatever they want on the table.</p><p>The idea boils down to allowing the user to create their own query strings defining a list of AND operations they wish to perform on the tables. Our job will be to parse this query and create the <a href="https://javarevisited.blogspot.com/2021/05/java-8-stream-lambda-expression-d.html">Predicate</a> for them. The following will be the format of the query:</p><blockquote><strong>&lt;Key&gt;&lt;Operator&gt;&lt;Value&gt;,&lt;Key&gt;&lt;Operator&gt;&lt;Value&gt;</strong></blockquote><p><strong>Key —</strong> It’s basically the field names from Entity class, for Nested fields, it&#39;s a slightly different approach. In the Post entity, there is a postType field. To use Id field of PostType entity in predicate, we need to use postType.id in predicate but dots will impact parsing from controller, so we create a custom mapping by creating a custom key postType that maps to postType.id .</p><p><strong>Operators —</strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/98e57e6427fa127f200c62e4f2e11649/href">https://medium.com/media/98e57e6427fa127f200c62e4f2e11649/href</a></iframe><p><strong>Value — </strong>It can be anything of type string, dates, integers, or doubles.</p><blockquote><strong>Usage</strong></blockquote><p>Filter to show Blogs containing title <strong>xyz — </strong>title-xyz</p><p>Filter to offer Motivational Blogs — postType:2 (motivation type id is 2)</p><p>Filter to show Blogs created between two dates — createdAt()2022–09–01,2022–09–10</p><h3><strong>Creating a Search Criteria</strong></h3><p>We will define a single search criterion as follow</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8c32a6a5b0a9d7d0ee18a052484ff75f/href">https://medium.com/media/8c32a6a5b0a9d7d0ee18a052484ff75f/href</a></iframe><h3>Common Predicate class</h3><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/bfff49d369e3ea7ae092108a794f56d8/href">https://medium.com/media/bfff49d369e3ea7ae092108a794f56d8/href</a></iframe><p>Let’s understand the above class. As you can see, it has a method getPredicate that will generate a new BooleanExpression predicate based on the SearchCriteria passed.</p><p>To do this I am using implementations of the QueryDSL Path class. These classes contain a reference to the property on the object you are looking to query and can be given comparison operators to build a Predicate.</p><p>As you can see, I’m using reflection to determine the class of the Key that this is passed.</p><p>Moving along, now what we need is a way to parse a whole query string into a bunch of SearchCriteria and then build a combined Predicate from the entire query. That class might look like the following</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/36293cc7fc3f14e9d86add314dea7a4a/href">https://medium.com/media/36293cc7fc3f14e9d86add314dea7a4a/href</a></iframe><p>For now, the important method is the from(String search) method. This method uses regex to create SearchCriteria from a query string. Then the build takes each of the criteria, uses the CommonPredicate to create Predicates, and then combines them all together as AND operations, returning a final Predicate. This predicate can then be sent straight to our repository!</p><h3>Hooking up with Service and Controller class</h3><p>The Service class essentially formats the filters into search criteria, gets the BooleanExpression from the auto-generated Predicates, and passes it to the Repository.</p><p>The <a href="https://javarevisited.blogspot.com/2022/05/how-to-return-json-xml-or-thymeleaf-.html">Controller</a> class gets the filters passed from the client and passes them to Service. As you can see below, we can pass multiple query params to build the query which clients need to filter on the table and its related tables.</p><figure><a href="https://javarevisited.blogspot.com/2022/02/spring-boot-restful-web-service-example-tutorial.html"><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Co0E8khD3lN_ZCPBM32a_w.png" /></a></figure><blockquote><em>If you liked the article please take a minute to offer me a clap 👏 (you can clap multiple times), follow me, or even buy me a coffee </em><a href="https://www.buymeacoffee.com/abhiandy">https://www.buymeacoffee.com/abhiandy</a></blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fdb0d5d3555b" width="1" height="1" alt=""><hr><p><a href="https://medium.com/javarevisited/dynamic-query-predicate-generation-using-springboot-and-querydsl-fdb0d5d3555b">Dynamic Query Predicate generation using SpringBoot and QueryDSL</a> was originally published in <a href="https://medium.com/javarevisited">Javarevisited</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>