<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:dc="http://purl.org/dc/elements/1.1/">
  <channel>
    <title>DEV Community: Dmitry Protsenko</title>
    <description>The latest articles on DEV Community by Dmitry Protsenko (@protsenko).</description>
    <link>https://dev.to/protsenko</link>
    <image>
      <url>https://media2.dev.to/dynamic/image/width=90,height=90,fit=cover,gravity=auto,format=auto/https:%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Fuser%2Fprofile_image%2F3026459%2F0811c74c-1143-4415-8a97-f725a3ecdfa5.png</url>
      <title>DEV Community: Dmitry Protsenko</title>
      <link>https://dev.to/protsenko</link>
    </image>
    <atom:link rel="self" type="application/rss+xml" href="https://dev.to/feed/protsenko"/>
    <language>en</language>
    <item>
      <title>IntelliJ IDEA Plugin Development: What Have I Learned</title>
      <dc:creator>Dmitry Protsenko</dc:creator>
      <pubDate>Mon, 16 Nov 2026 15:00:00 +0000</pubDate>
      <link>https://dev.to/protsenko/intellij-idea-plugin-development-what-have-i-learned-9bh</link>
      <guid>https://dev.to/protsenko/intellij-idea-plugin-development-what-have-i-learned-9bh</guid>
      <description>&lt;p&gt;Almost a year has passed since I began developing a Docker and Kubernetes security scanner deeply integrated into an IDE. I have collected many different thoughts on IntelliJ IDEA plugin development, from building inspections to debugging and maintaining them.&lt;/p&gt;

&lt;p&gt;My article &lt;a href="https://protsenko.dev/2025/03/24/how-i-made-docker-linter-for-intellij-idea-and-other-jetbrains-ide/" rel="noopener noreferrer"&gt;IntelliJ Plugin: Building Docker Security Analysis Tools&lt;/a&gt; was the first article in my blog and was more generic. In this article, I explain a bit more about the technical staff that I’m using in my work. I hope you will enjoy the article. Let’s dive into IntelliJ IDEA plugin development.&lt;/p&gt;

&lt;h2&gt;
  
  
  Table of contents
&lt;/h2&gt;

&lt;ul&gt;
&lt;li&gt;Quick Intro to Inspections&lt;/li&gt;
&lt;li&gt;
IntelliJ IDEA Inspections Best Practices

&lt;ul&gt;
&lt;li&gt;Do not use raw PsiElementVisitor&lt;/li&gt;
&lt;li&gt;Verifications should be flexible&lt;/li&gt;
&lt;li&gt;Take care of plugin internalization&lt;/li&gt;
&lt;li&gt;Take care of performance&lt;/li&gt;
&lt;li&gt;Extend an IntelliJ IDEA plugin with extension points&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;li&gt;
The IntelliJ IDEA testing approach

&lt;ul&gt;
&lt;li&gt;The good test shouldn’t take a lot of your time&lt;/li&gt;
&lt;li&gt;Act as a user to test a plugin&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;li&gt;
Managing releases for the IntelliJ IDEA plugin

&lt;ul&gt;
&lt;li&gt;Planning and Development&lt;/li&gt;
&lt;li&gt;The Plugin version and its changelog&lt;/li&gt;
&lt;li&gt;A bit about GitHub actions&lt;/li&gt;
&lt;li&gt;Write documentation and content&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;li&gt;Next Steps in IntelliJ IDEA Plugin Development&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;The Cloud Security plugin for IntelliJ IDEA contains a lot of bundled rules pointing to Docker and Kubernetes Security. To implement them, we need to use a mechanism called &lt;code&gt;Inspections&lt;/code&gt; which provides a tool for static code analysis.&lt;/p&gt;

&lt;h2&gt;
  
  
  Quick Intro to Inspections
&lt;/h2&gt;

&lt;p&gt;Inspections in the JetBrains IDEs are special classes that check your code for specific issues. Inspections are defined by creating a class that extends &lt;code&gt;LocalInspectionTool&lt;/code&gt; or its inheritance. The class will be used to implement logic inspection, which is a common task in IntelliJ IDEA plugin development&lt;/p&gt;

&lt;p&gt;Analysis performed with special &lt;code&gt;Visitor&lt;/code&gt; classes. Those classes provide a way to analyze the whole file or specific parts of the analyzed file. These visitors’ classes are used for walking across the file, getting their PSI elements.&lt;/p&gt;

&lt;p&gt;PSI is the Program Structure Interface, the syntactic and semantic code model that powers many of the platform’s features, especially code inspections. For example, different Docker commands represent classes like &lt;code&gt;DockerFileFromCommand&lt;/code&gt;, &lt;code&gt;DockerFileRunCommand&lt;/code&gt;, etc.&lt;/p&gt;

&lt;p&gt;The &lt;code&gt;PsiElement&lt;/code&gt; is a primitive in a PSI world. The &lt;code&gt;PsiElement&lt;/code&gt; is an interface for any other PSI classes, such as &lt;code&gt;PsiFile&lt;/code&gt; or &lt;code&gt;PsiComment&lt;/code&gt;, from the &lt;code&gt;PsiElementVisitor&lt;/code&gt; interface. There are a lot of different PSI elements that have already been implemented.&lt;/p&gt;

&lt;p&gt;By receiving the needed PSI elements, we could analyze them and highlight those elements in the document.&lt;/p&gt;

&lt;p&gt;In the &lt;a href="https://plugins.jetbrains.com/plugin/25413-cloud-iac-security" rel="noopener noreferrer"&gt;Docker scanner plugin&lt;/a&gt;, I used PSI classes from the IntelliJ Docker plugin to analyze Docker files and commands. There are ways you could find what PSI elements you should analyze (from junior to senior approach):&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Implement a visitor and log each PSI element with its text.&lt;/li&gt;
&lt;li&gt;Stop in debug mode in the visitor and watch what PSI elements are visited.&lt;/li&gt;
&lt;li&gt;Do the same, but with auto tests (I’ll explain them in more detail further)&lt;/li&gt;
&lt;li&gt;Use the PsiViewer feature by enabling internal functions. There is a &lt;a href="https://plugins.jetbrains.com/docs/intellij/explore-api.html#internalMode" rel="noopener noreferrer"&gt;guide&lt;/a&gt;.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Note: To use PSI elements (their classes) from external plugins like Docker, you have to declare them as a dependency. Read more on the IntelliJ Platform SDK &lt;a href="https://plugins.jetbrains.com/docs/intellij/plugin-dependencies.html" rel="noopener noreferrer"&gt;site&lt;/a&gt;.&lt;/p&gt;

&lt;h2&gt;
  
  
  IntelliJ IDEA Inspections Best Practices
&lt;/h2&gt;

&lt;p&gt;Let’s build a synthetic inspection to show how it works. Let’s try to find sudo &lt;code&gt;rm -rf /&lt;/code&gt; in RUN commands and highlight it.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight kotlin"&gt;&lt;code&gt;&lt;span class="k"&gt;const&lt;/span&gt; &lt;span class="kd"&gt;val&lt;/span&gt; &lt;span class="py"&gt;MALICIOUS_RM_RF_COMMAND&lt;/span&gt; &lt;span class="p"&gt;=&lt;/span&gt; &lt;span class="s"&gt;"rm -rf /"&lt;/span&gt;

&lt;span class="kd"&gt;class&lt;/span&gt; &lt;span class="nc"&gt;SudoRmRfInspection&lt;/span&gt; &lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="nc"&gt;LocalInspectionTool&lt;/span&gt;&lt;span class="p"&gt;()&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
    &lt;span class="k"&gt;override&lt;/span&gt; &lt;span class="k"&gt;fun&lt;/span&gt; &lt;span class="nf"&gt;buildVisitor&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;
        &lt;span class="n"&gt;holder&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="nc"&gt;ProblemsHolder&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
        &lt;span class="n"&gt;isOnTheFly&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="nc"&gt;Boolean&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
    &lt;span class="p"&gt;):&lt;/span&gt; &lt;span class="nc"&gt;PsiElementVisitor&lt;/span&gt; &lt;span class="p"&gt;=&lt;/span&gt;
        &lt;span class="kd"&gt;object&lt;/span&gt; &lt;span class="err"&gt;: &lt;/span&gt;&lt;span class="nc"&gt;PsiElementVisitor&lt;/span&gt;&lt;span class="p"&gt;()&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
            &lt;span class="k"&gt;override&lt;/span&gt; &lt;span class="k"&gt;fun&lt;/span&gt; &lt;span class="nf"&gt;visitElement&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;element&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="nc"&gt;PsiElement&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
                &lt;span class="k"&gt;if&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;element&lt;/span&gt; &lt;span class="k"&gt;is&lt;/span&gt; &lt;span class="nc"&gt;DockerFileRunCommand&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
                    &lt;span class="k"&gt;if&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;element&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;text&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;contains&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nc"&gt;MALICIOUS_RM_RF_COMMAND&lt;/span&gt;&lt;span class="p"&gt;))&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
                        &lt;span class="n"&gt;holder&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;registerProblem&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;
                            &lt;span class="n"&gt;element&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
                            &lt;span class="s"&gt;"Malicious rm -rf / command found"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
                            &lt;span class="nc"&gt;ProblemHighlightType&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nc"&gt;ERROR&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
                        &lt;span class="p"&gt;)&lt;/span&gt;
                    &lt;span class="p"&gt;}&lt;/span&gt;
                &lt;span class="p"&gt;}&lt;/span&gt;
                &lt;span class="k"&gt;super&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;visitElement&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;element&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
            &lt;span class="p"&gt;}&lt;/span&gt;
        &lt;span class="p"&gt;}&lt;/span&gt;
&lt;span class="p"&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;There is no rocket science in this step. We did an Inspection and overrode the build visitor function with its visitor. Each time our visitor visits elements, we check whether it is a Docker run command or not. When we’ve got it, we simply look inside the element’s text, compare it with malicious text, and highlight the malicious text by registering the problem in the holder.&lt;/p&gt;

&lt;p&gt;While straightforward, this approach has design drawbacks and can be improved according to best practices in IntelliJ IDEA plugin development for cleaner and more efficient inspections.&lt;/p&gt;

&lt;h3&gt;
  
  
  Do not use raw PsiElementVisitor
&lt;/h3&gt;

&lt;p&gt;The PsiElementVisitor is too low-level. You’ve got to find the proper inheritance of the element visitor or implement it yourself. In the plugin, I’m using &lt;code&gt;DockerFileVisitor&lt;/code&gt; from the Docker plugin, but at the start, I implemented my own and switched to a plugin one later.&lt;/p&gt;

&lt;p&gt;The better way to find a proper visitor is by looking into sources. If you know what inspections are provided by a plugin, you could find the implementation in the sources. This is how I found that I could use.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight kotlin"&gt;&lt;code&gt;&lt;span class="k"&gt;const&lt;/span&gt; &lt;span class="kd"&gt;val&lt;/span&gt; &lt;span class="py"&gt;MALICIOUS_RM_RF_COMMAND&lt;/span&gt; &lt;span class="p"&gt;=&lt;/span&gt; &lt;span class="s"&gt;"rm -rf /"&lt;/span&gt;

&lt;span class="kd"&gt;class&lt;/span&gt; &lt;span class="nc"&gt;SudoRmRfInspection&lt;/span&gt; &lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="nc"&gt;LocalInspectionTool&lt;/span&gt;&lt;span class="p"&gt;()&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
    &lt;span class="k"&gt;override&lt;/span&gt; &lt;span class="k"&gt;fun&lt;/span&gt; &lt;span class="nf"&gt;buildVisitor&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;
        &lt;span class="n"&gt;holder&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="nc"&gt;ProblemsHolder&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
        &lt;span class="n"&gt;isOnTheFly&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="nc"&gt;Boolean&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
    &lt;span class="p"&gt;):&lt;/span&gt; &lt;span class="nc"&gt;PsiElementVisitor&lt;/span&gt; &lt;span class="p"&gt;=&lt;/span&gt;
        &lt;span class="kd"&gt;object&lt;/span&gt; &lt;span class="err"&gt;: &lt;/span&gt;&lt;span class="nc"&gt;DockerFileVisitor&lt;/span&gt;&lt;span class="p"&gt;()&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
            &lt;span class="k"&gt;override&lt;/span&gt; &lt;span class="k"&gt;fun&lt;/span&gt; &lt;span class="nf"&gt;visitRunCommand&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;o&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="nc"&gt;DockerFileRunCommand&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
                &lt;span class="k"&gt;if&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;o&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;text&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;contains&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nc"&gt;MALICIOUS_RM_RF_COMMAND&lt;/span&gt;&lt;span class="p"&gt;))&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
                    &lt;span class="n"&gt;holder&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;registerProblem&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;
                        &lt;span class="n"&gt;o&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
                        &lt;span class="s"&gt;"Malicious rm -rf / command found"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
                        &lt;span class="nc"&gt;ProblemHighlightType&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nc"&gt;ERROR&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
                    &lt;span class="p"&gt;)&lt;/span&gt;
                &lt;span class="p"&gt;}&lt;/span&gt;
            &lt;span class="p"&gt;}&lt;/span&gt;
        &lt;span class="p"&gt;}&lt;/span&gt;
&lt;span class="p"&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h3&gt;
  
  
  Verifications should be flexible
&lt;/h3&gt;

&lt;p&gt;Verification in code using &lt;code&gt;contains&lt;/code&gt; made inspection less flexible. One space between, and an inspection couldn’t find this problem. When implementing verification, you should care about as many variants of the problem as you can imagine. Do not point only to one pattern. There could be a lot of them. The best you could do is collect these cases and cover them with automatic tests.&lt;/p&gt;

&lt;p&gt;This practice also improves your knowledge about inspection, as you can learn a lot about the problem to provide quality inspection.&lt;/p&gt;

&lt;h3&gt;
  
  
  Take care of plugin internalization
&lt;/h3&gt;

&lt;p&gt;You should care about internalizing your strings and not use them directly as written. You should create your own resource bundle and read strings from it; it will improve the internationalization process. There is a more detailed &lt;a href="https://plugins.jetbrains.com/docs/intellij/internationalization.html" rel="noopener noreferrer"&gt;guide&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;Proper internalization is essential for delivering polished, globally usable plugins in professional IntelliJ IDEA plugin development&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight kotlin"&gt;&lt;code&gt;&lt;span class="c1"&gt;// SecurityPluginBundle.kt&lt;/span&gt;
&lt;span class="nd"&gt;@NonNls&lt;/span&gt;
&lt;span class="k"&gt;private&lt;/span&gt; &lt;span class="k"&gt;const&lt;/span&gt; &lt;span class="kd"&gt;val&lt;/span&gt; &lt;span class="py"&gt;BUNDLE&lt;/span&gt; &lt;span class="p"&gt;=&lt;/span&gt; &lt;span class="s"&gt;"messages.SecurityPluginBundle"&lt;/span&gt;

&lt;span class="kd"&gt;object&lt;/span&gt; &lt;span class="nc"&gt;SecurityPluginBundle&lt;/span&gt; &lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="nc"&gt;DynamicBundle&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nc"&gt;BUNDLE&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
    &lt;span class="nd"&gt;@JvmStatic&lt;/span&gt;
    &lt;span class="k"&gt;fun&lt;/span&gt; &lt;span class="nf"&gt;message&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;
        &lt;span class="nd"&gt;@PropertyKey&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;resourceBundle&lt;/span&gt; &lt;span class="p"&gt;=&lt;/span&gt; &lt;span class="nc"&gt;BUNDLE&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="n"&gt;key&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="nc"&gt;String&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
        &lt;span class="k"&gt;vararg&lt;/span&gt; &lt;span class="n"&gt;params&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="nc"&gt;Any&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
    &lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="p"&gt;=&lt;/span&gt; &lt;span class="nf"&gt;getMessage&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;key&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="p"&gt;*&lt;/span&gt;&lt;span class="n"&gt;params&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;

    &lt;span class="nd"&gt;@Suppress&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s"&gt;"unused"&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
    &lt;span class="nd"&gt;@JvmStatic&lt;/span&gt;
    &lt;span class="k"&gt;fun&lt;/span&gt; &lt;span class="nf"&gt;messagePointer&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;
        &lt;span class="nd"&gt;@PropertyKey&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;resourceBundle&lt;/span&gt; &lt;span class="p"&gt;=&lt;/span&gt; &lt;span class="nc"&gt;BUNDLE&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="n"&gt;key&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="nc"&gt;String&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
        &lt;span class="k"&gt;vararg&lt;/span&gt; &lt;span class="n"&gt;params&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="nc"&gt;Any&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
    &lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="p"&gt;=&lt;/span&gt; &lt;span class="nf"&gt;getLazyMessage&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;key&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="p"&gt;*&lt;/span&gt;&lt;span class="n"&gt;params&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
&lt;span class="p"&gt;}&lt;/span&gt;
&lt;span class="c1"&gt;// SecurityPluginBundle.properties&lt;/span&gt;
&lt;span class="n"&gt;inspection&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;text&lt;/span&gt;&lt;span class="p"&gt;=&lt;/span&gt;&lt;span class="nc"&gt;Malicious&lt;/span&gt; &lt;span class="n"&gt;rm&lt;/span&gt; &lt;span class="p"&gt;-&lt;/span&gt;&lt;span class="n"&gt;rf&lt;/span&gt; &lt;span class="p"&gt;/&lt;/span&gt; &lt;span class="n"&gt;command&lt;/span&gt; &lt;span class="n"&gt;found&lt;/span&gt;
&lt;span class="c1"&gt;// Usage&lt;/span&gt;
&lt;span class="nc"&gt;SecurityPluginBundle&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;message&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s"&gt;"inspection.text"&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h3&gt;
  
  
  Take care of performance
&lt;/h3&gt;

&lt;p&gt;Using &lt;code&gt;getText&lt;/code&gt; from PSI elements could cost you performance traversing the whole tree under the given element, and concatenates strings, consider using &lt;code&gt;textMatches()&lt;/code&gt; [&lt;a href="https://plugins.jetbrains.com/docs/intellij/psi-performance.html#avoid-expensive-methods-of-psielement" rel="noopener noreferrer"&gt;proof&lt;/a&gt;]. Actually, it wouldn’t be dramatic in the case of using for small PSI elements. In the proof I provided, you could learn more about performance.&lt;/p&gt;

&lt;p&gt;Hold in mind that your inspection code will execute almost every change in the code by default. There shouldn’t be slow operations. Imagine the user typing 100 symbols in a minute. Your inspection could be executed 100 times.&lt;/p&gt;

&lt;p&gt;However, this tip applies not only to plugin development but also to common software development. Try to avoid premature optimization as it is a source of evil :)&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight kotlin"&gt;&lt;code&gt;&lt;span class="c1"&gt;// old&lt;/span&gt;
&lt;span class="n"&gt;o&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;text&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;contains&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nc"&gt;MALICIOUS_RM_RF_COMMAND&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
&lt;span class="c1"&gt;// new&lt;/span&gt;
&lt;span class="n"&gt;o&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;textMatches&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nc"&gt;MALICIOUS_RM_RF_COMMAND&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h3&gt;
  
  
  Extend an IntelliJ IDEA plugin with extension points
&lt;/h3&gt;

&lt;p&gt;Let’s stop roasting example inspections and move forward. The next cool thing that I implemented in the plugin is using extension points for faster inspection development, but let’s try to find out what it is and what problem it could solve.&lt;/p&gt;

&lt;p&gt;Imagine you need to implement one more inspection, I would say it will be using sudo in run commands. From this point, you have two ways, and one with:&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Implement one more inspection&lt;/strong&gt;. Actually, it would be the easiest path, but each time you create an inspection in the plugin, you have to take care of at least the following things:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Register it in the &lt;code&gt;plugin.xml&lt;/code&gt; (it’s pretty easy)&lt;/li&gt;
&lt;li&gt;Write an HTML file with a description (sooo boring!)&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;Implement additional verification in the previous inspection&lt;/strong&gt; and rename the inspection class to be more generic. By using this approach, you slightly update the HTML file, and it works. But what if you need to implement 20 inspections? It would be a mess in the class.&lt;/p&gt;

&lt;p&gt;If you don’t want to register inspections each time, you could use the latest approach by using extension points. What are the extension points? Extension points provide a way for other plugins to extend your plugin functionality, and you could use them in your own way.&lt;/p&gt;

&lt;p&gt;There are two types of extension points: &lt;em&gt;interface&lt;/em&gt; and &lt;em&gt;bean&lt;/em&gt; extensions. We need to focus on the first one. In the plugin, you could declare an interface and register it in &lt;code&gt;plugin.xml&lt;/code&gt;, and implement its class. With this approach, you could dynamically load all the implementations of the interface.&lt;/p&gt;

&lt;p&gt;Here’s a small example of how you might declare an extension point interface and its implementations to speed up inspection development in intellij idea plugin development:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight kotlin"&gt;&lt;code&gt;&lt;span class="k"&gt;const&lt;/span&gt; &lt;span class="kd"&gt;val&lt;/span&gt; &lt;span class="py"&gt;MALICIOUS_RM_RF_COMMAND&lt;/span&gt; &lt;span class="p"&gt;=&lt;/span&gt; &lt;span class="s"&gt;"rm -rf /"&lt;/span&gt;

&lt;span class="c1"&gt;// Declaring interface of extension point&lt;/span&gt;
&lt;span class="kd"&gt;interface&lt;/span&gt; &lt;span class="nc"&gt;DockerfileRunAnalyzer&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
    &lt;span class="k"&gt;fun&lt;/span&gt; &lt;span class="nf"&gt;handle&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;
        &lt;span class="n"&gt;runCommand&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="nc"&gt;String&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
        &lt;span class="n"&gt;psiElement&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="nc"&gt;PsiElement&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
        &lt;span class="n"&gt;holder&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="nc"&gt;ProblemsHolder&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
    &lt;span class="p"&gt;)&lt;/span&gt;
&lt;span class="p"&gt;}&lt;/span&gt;

&lt;span class="c1"&gt;// Make an analyzer class and extend it with our extension point&lt;/span&gt;
&lt;span class="kd"&gt;class&lt;/span&gt; &lt;span class="nc"&gt;RmRfAnalyzer&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="nc"&gt;DockerfileRunAnalyzer&lt;/span&gt;&lt;span class="p"&gt;{&lt;/span&gt;
    &lt;span class="k"&gt;override&lt;/span&gt; &lt;span class="k"&gt;fun&lt;/span&gt; &lt;span class="nf"&gt;handle&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;
        &lt;span class="n"&gt;runCommand&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="nc"&gt;String&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
        &lt;span class="n"&gt;psiElement&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="nc"&gt;PsiElement&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
        &lt;span class="n"&gt;holder&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="nc"&gt;ProblemsHolder&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
    &lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
        &lt;span class="k"&gt;if&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;runCommand&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;contains&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nc"&gt;MALICIOUS_RM_RF_COMMAND&lt;/span&gt;&lt;span class="p"&gt;))&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
            &lt;span class="n"&gt;holder&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;registerProblem&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;
                &lt;span class="n"&gt;psiElement&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
                &lt;span class="nc"&gt;SecurityPluginBundle&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;message&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s"&gt;"inspection.text"&lt;/span&gt;&lt;span class="p"&gt;),&lt;/span&gt;
                &lt;span class="nc"&gt;ProblemHighlightType&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nc"&gt;ERROR&lt;/span&gt;
            &lt;span class="p"&gt;)&lt;/span&gt;
        &lt;span class="p"&gt;}&lt;/span&gt;
    &lt;span class="p"&gt;}&lt;/span&gt;
&lt;span class="p"&gt;}&lt;/span&gt;

&lt;span class="c1"&gt;// Read all extension points and run them&lt;/span&gt;
&lt;span class="kd"&gt;class&lt;/span&gt; &lt;span class="nc"&gt;RunCommandInspection&lt;/span&gt; &lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="nc"&gt;LocalInspectionTool&lt;/span&gt;&lt;span class="p"&gt;()&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
    &lt;span class="k"&gt;override&lt;/span&gt; &lt;span class="k"&gt;fun&lt;/span&gt; &lt;span class="nf"&gt;buildVisitor&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;
        &lt;span class="n"&gt;holder&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="nc"&gt;ProblemsHolder&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
        &lt;span class="n"&gt;isOnTheFly&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="nc"&gt;Boolean&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
    &lt;span class="p"&gt;):&lt;/span&gt; &lt;span class="nc"&gt;PsiElementVisitor&lt;/span&gt; &lt;span class="p"&gt;=&lt;/span&gt;
        &lt;span class="kd"&gt;object&lt;/span&gt; &lt;span class="err"&gt;: &lt;/span&gt;&lt;span class="nc"&gt;DockerFileVisitor&lt;/span&gt;&lt;span class="p"&gt;()&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
            &lt;span class="k"&gt;override&lt;/span&gt; &lt;span class="k"&gt;fun&lt;/span&gt; &lt;span class="nf"&gt;visitRunCommand&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;o&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="nc"&gt;DockerFileRunCommand&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
                &lt;span class="kd"&gt;val&lt;/span&gt; &lt;span class="py"&gt;extensionPointName&lt;/span&gt; &lt;span class="p"&gt;=&lt;/span&gt;
                    &lt;span class="nc"&gt;ExtensionPointName&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;create&lt;/span&gt;&lt;span class="p"&gt;&amp;lt;&lt;/span&gt;&lt;span class="nc"&gt;DockerfileRunAnalyzer&lt;/span&gt;&lt;span class="p"&gt;&amp;gt;(&lt;/span&gt;&lt;span class="s"&gt;"dev.protsenko.security-linter.dockerFileRunAnalyzer"&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;

                &lt;span class="kd"&gt;val&lt;/span&gt; &lt;span class="py"&gt;runCommand&lt;/span&gt; &lt;span class="p"&gt;=&lt;/span&gt; &lt;span class="n"&gt;o&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;text&lt;/span&gt;

                &lt;span class="k"&gt;for&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;extension&lt;/span&gt; &lt;span class="k"&gt;in&lt;/span&gt; &lt;span class="n"&gt;extensionPointName&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;extensions&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
                    &lt;span class="n"&gt;extension&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;handle&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;runCommand&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;o&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;holder&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
                &lt;span class="p"&gt;}&lt;/span&gt;
            &lt;span class="p"&gt;}&lt;/span&gt;
        &lt;span class="p"&gt;}&lt;/span&gt;
&lt;span class="p"&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;What was changed? Now, to implement inspections that analyze run commands, you only have to implement the analyzer class and register it in the extension points. With this solution, you won’t have a mess in one class if you need to implement many inspections.&lt;/p&gt;

&lt;p&gt;What additional pros of this approach? With 20 dedicated inspections, you will spawn 20 different inspections instead of one. The examples are less complex than the real ones. With real ones, you have to detect complex cases by covering more IntelliJ platform methods.&lt;/p&gt;

&lt;p&gt;There are some cons to using it. It’s more about user experience. If you have only one inspection for 20 different rules, the user could disable all of them, not just what they need. Implementing suppression as a code feature in your inspection would also be a problem. Suppressing one problem will extend to every problem in this inspection. In this case, you have to provide a more complex UI for your plugin instead of relying on platform ones.&lt;/p&gt;

&lt;p&gt;The last problems were acceptable to me because they improved performance and skipped the routine building of HTML inspection description files.&lt;/p&gt;

&lt;h2&gt;
  
  
  The IntelliJ IDEA testing approach
&lt;/h2&gt;

&lt;p&gt;Tests are the foundation for your plugin. You must write them. Basic inspections have many test cases, and testing them manually is painful. What if you need to test 40 test cases after refactoring? It’s shooting yourself in the foot! Stop this violence, keep calm, read &lt;a href="https://plugins.jetbrains.com/docs/intellij/testing-plugins.html" rel="noopener noreferrer"&gt;testing documentation&lt;/a&gt;, and start writing tests.&lt;/p&gt;

&lt;p&gt;I wrote many test cases and have 85% test coverage on the code lines to ensure everything worked correctly. This significantly increased my development speed and protected me from technical debt.&lt;/p&gt;

&lt;p&gt;However, tests did not catch some issues, such as compatibility problems with different IDE versions. Initially, I adapted my plugin for version 233 and newer. I practiced TDD, developed inspections based on test feedback, and performed manual testing on the targeted IDE version (233). However, I was quite surprised when I installed the plugin on the latest IDE version and saw that my highlighting blinked or disappeared occasionally.&lt;/p&gt;

&lt;h3&gt;
  
  
  The good test shouldn’t take a lot of your time
&lt;/h3&gt;

&lt;p&gt;There are many ways to develop tests. I highly recommend learning carefully what the IntelliJ platform offers for testing because it has an excellent framework for this. As the IntelliJ plugin developer, I highly recommend writing tests that cover inspections and, if possible, writing unit tests for helper methods and other code.&lt;/p&gt;

&lt;p&gt;In the code base I’m using &lt;code&gt;BasePlatformTestCase&lt;/code&gt; , and extend my classes from it. I’m using an approach with my abstract class &lt;code&gt;InspectionBaseTest&lt;/code&gt;, which provides everything I need to test inspections.&lt;/p&gt;

&lt;p&gt;Let’s see the result of my work:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight kotlin"&gt;&lt;code&gt;&lt;span class="kd"&gt;class&lt;/span&gt; &lt;span class="nc"&gt;DFS030ApkNoCacheTest&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;
    &lt;span class="k"&gt;override&lt;/span&gt; &lt;span class="kd"&gt;val&lt;/span&gt; &lt;span class="py"&gt;ruleFolderName&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="nc"&gt;String&lt;/span&gt; &lt;span class="p"&gt;=&lt;/span&gt; &lt;span class="s"&gt;"DFS030"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
    &lt;span class="k"&gt;override&lt;/span&gt; &lt;span class="kd"&gt;val&lt;/span&gt; &lt;span class="py"&gt;customFiles&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="nc"&gt;Set&lt;/span&gt;&lt;span class="p"&gt;&amp;lt;&lt;/span&gt;&lt;span class="nc"&gt;String&lt;/span&gt;&lt;span class="p"&gt;&amp;gt;&lt;/span&gt; &lt;span class="p"&gt;=&lt;/span&gt; &lt;span class="nf"&gt;emptySet&lt;/span&gt;&lt;span class="p"&gt;(),&lt;/span&gt;
    &lt;span class="k"&gt;override&lt;/span&gt; &lt;span class="kd"&gt;val&lt;/span&gt; &lt;span class="py"&gt;targetInspection&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="nc"&gt;LocalInspectionTool&lt;/span&gt; &lt;span class="p"&gt;=&lt;/span&gt; &lt;span class="nc"&gt;DockerfileRunInspection&lt;/span&gt;&lt;span class="p"&gt;(),&lt;/span&gt;
&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="nc"&gt;DockerHighlightingBaseTest&lt;/span&gt;&lt;span class="p"&gt;()&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;As you can see, I only set a folder name with test data and provided an inspection for testing. Each test verifies valid and invalid files. If I want to cover more cases, I specify test files in the custom files field.&lt;/p&gt;

&lt;p&gt;That’s all! You don’t have to spend time writing a lot of code to test something. Just prepare your base depending on your logic and inspections, and reuse it. Here is my suggestion – spend time on your testing framework on your needs.&lt;/p&gt;

&lt;h3&gt;
  
  
  Act as a user to test a plugin
&lt;/h3&gt;

&lt;p&gt;Automated tests are good, they are very helpful, and save you nerves during refactorings. However, even if you are close to 100% testing coverage, you have to manually test how your inspections or functionality work.&lt;/p&gt;

&lt;p&gt;This shouldn’t be a surprise, but tests covered only a small percentage of things, depending on your cases. During manual testing, ask yourself:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Is it easy to set up and use your plugin?&lt;/li&gt;
&lt;li&gt;Is highlighting consistent? It could blink, inspection messages could be in different formats, delays due to poor performance could occur, etc.&lt;/li&gt;
&lt;li&gt;Are there any other problems during using your plugin?&lt;/li&gt;
&lt;li&gt;Is it suitable to record a video demo of your product? This is a really good question because I tried to do this, but found different issues with it.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Just be a user of what you’re developing. Manual testing should be performed every time you develop and release something. Spend 10 minutes testing your changes to make sure everything is all right.&lt;/p&gt;

&lt;h2&gt;
  
  
  Managing releases for the IntelliJ IDEA plugin
&lt;/h2&gt;

&lt;p&gt;I’m trying to be consistent in the plugin updates. Every one or two weeks, I publish updates with new inspections or bug fixes. To be consistent in the updates, I have several steps that I should perform before uploading the plugin.&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Plan and develop inspections.&lt;/li&gt;
&lt;li&gt;Cover it with test automation and perform a manual one.&lt;/li&gt;
&lt;li&gt;Update the version and its changelog.&lt;/li&gt;
&lt;li&gt;Commit and push changes to GitHub.&lt;/li&gt;
&lt;li&gt;With GitHub actions, I do one more automated test run to double-check.&lt;/li&gt;
&lt;li&gt;Write a documentation page about new inspections in my blog.&lt;/li&gt;
&lt;li&gt;…and finally build the plugin and upload it.&lt;/li&gt;
&lt;/ul&gt;

&lt;h3&gt;
  
  
  Planning and Development
&lt;/h3&gt;

&lt;p&gt;I have nothing special. I did research on possible inspections and just took them one by one. For Docker inspections, I analyzed Trivy and Hadolint rulesets, and for Kubernetes, I used Pod Security Standards with a look at Kubescape rego rules.&lt;/p&gt;

&lt;p&gt;I used &lt;a href="https://github.com/NordCoderd/cloud-security-plugin/issues?q=is%3Aissue%20state%3Aclosed" rel="noopener noreferrer"&gt;GitHub issues&lt;/a&gt; to store lists of rules, but lately, I have declined this solution as no one wants to contribute or create issues. Now, I hold the list of planned features in Apple Notes and choose what I want to do from this list.&lt;/p&gt;

&lt;h3&gt;
  
  
  The Plugin version and its changelog
&lt;/h3&gt;

&lt;p&gt;Regarding the version and changelog, if you’ve used the plugin template from scratch like me, you’re probably familiar with how it works, but if not, I’ll tell you.&lt;/p&gt;

&lt;p&gt;The plugin template comes with preconfigured Gradle files and properties. If you’re updating the plugin version, you have to update the changelog file in the proper format. Changes in the changelog file automatically come to the release notes on the marketplace for your plugin. If you haven’t done this, the build will fail. Proper versioning and changelog upkeep are essential best practices in IntelliJ IDEA plugin development to ensure smooth releases and marketplace integration.&lt;/p&gt;

&lt;h3&gt;
  
  
  A bit about GitHub actions
&lt;/h3&gt;

&lt;p&gt;Regarding GitHub actions, if you can use it, use it for building and running your tests. Double-checking wouldn’t be redundant, as you need to deliver good releases.&lt;/p&gt;

&lt;h3&gt;
  
  
  Write documentation and content
&lt;/h3&gt;

&lt;p&gt;Publishing updates involves many things, but there is more. With new inspections, I should write documentation on the detected problem. Each highlighted inspection provides a link to its documentation to give a user comprehensive information about the problem.&lt;/p&gt;

&lt;p&gt;From the start, I created a template for my article with a strong structure, but step by step, I’m trying to find a more comfortable format for users. These pages are read not only by plugin users but also by users from search engines like Google. So, recently, I started writing this documentation for different user groups and optimized it for search engines.&lt;/p&gt;

&lt;h2&gt;
  
  
  Next Steps in IntelliJ IDEA Plugin Development
&lt;/h2&gt;

&lt;p&gt;Developing plugins for JetBrains products is a wide area with many nuances. However, the journey into IntelliJ plugin development is very exciting and fun. Developing the plugin as a side project on weekends was a good idea, as I wanted to build something meaningful to me, share my knowledge about development, and strengthen my expertise in Docker and Kubernetes Security and Maintainability problems.&lt;/p&gt;

&lt;p&gt;If you want more, I highly recommend reading my &lt;a href="https://protsenko.dev/2025/03/24/how-i-made-docker-linter-for-intellij-idea-and-other-jetbrains-ide/" rel="noopener noreferrer"&gt;IntelliJ Plugin: Building Docker Security Analysis Tools&lt;/a&gt;. To learn about new articles, follow me on &lt;a href="https://www.linkedin.com/in/protsenkodev/" rel="noopener noreferrer"&gt;LinkedIn&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Want to build your own plugin first? Start with &lt;a href="https://protsenko.dev/2025/04/01/introduction-to-developing-a-plugin-for-intellij-idea/" rel="noopener noreferrer"&gt;IntelliJ Plugin Development: Build Your First Plugin&lt;/a&gt;.&lt;/strong&gt;&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;&lt;strong&gt;Found this useful?&lt;/strong&gt; Follow me on social media to stay updated.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://t.me/protsenko_dev" rel="noopener noreferrer"&gt;Telegram&lt;/a&gt; · &lt;a href="https://www.linkedin.com/in/protsenkodev/" rel="noopener noreferrer"&gt;LinkedIn&lt;/a&gt;&lt;/p&gt;
&lt;/blockquote&gt;

</description>
      <category>intellij</category>
      <category>kotlin</category>
      <category>plugins</category>
      <category>java</category>
    </item>
    <item>
      <title>AI Coding Workflow: TDD, Reviews, and Guardrails</title>
      <dc:creator>Dmitry Protsenko</dc:creator>
      <pubDate>Fri, 13 Nov 2026 15:00:00 +0000</pubDate>
      <link>https://dev.to/protsenko/ai-coding-workflow-tdd-reviews-and-guardrails-4bjk</link>
      <guid>https://dev.to/protsenko/ai-coding-workflow-tdd-reviews-and-guardrails-4bjk</guid>
      <description>&lt;p&gt;If you think AI-driven development makes you faster – probably you’re using it in wrong way. Faster development with AI produces more problems than benefits. Quality needs time and your attention.&lt;/p&gt;

&lt;p&gt;I would like to focus you on problems related to AI-driven development, and how I reduce them:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;AI doesn’t know the full context of the codebase and reinvents the wheel every single time.&lt;/li&gt;
&lt;li&gt;AI doesn’t know project specifics, business domain and automations around it.&lt;/li&gt;
&lt;li&gt;AI doesn’t know about all the constraints accepted in the project.&lt;/li&gt;
&lt;li&gt;AI writes just to write, it has no goal to produce correct and proper code with respect to common practices.&lt;/li&gt;
&lt;li&gt;AI will write a test to make it pass, not to actually test something.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;All of these are big problems, using AI blindly just to get the work done doesn’t lead to anything good, the codebase degrades faster, amount of issues stacks up iteration by iteration and it becomes noticeable with growing your codebase.&lt;/p&gt;

&lt;p&gt;To reduce the impact of such problems – you have to invest resources:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Into yourself because professionalism and expertise matters even more.&lt;/li&gt;
&lt;li&gt;Into the way you are working with AI.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;For a couple of months of active work with Claude and other agents I set up a working workflow for myself to reduce number of problems:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Firstly – spec work and plan of work, and only then coding. Such approach gives more predictable result for working with AI agents because each stage gives artifacts for the next one: specification, action plan, development.&lt;/li&gt;
&lt;li&gt;Development is done using test driven development – firstly red tests, then the code to make tests pass, not the other way around otherwise at some point AI starts to generate tests only to pass the test coverage check.&lt;/li&gt;
&lt;li&gt;Using &lt;a href="https://www.jetbrains.com/help/idea/mcp-server.html" rel="noopener noreferrer"&gt;IntelliJ IDEA MCP&lt;/a&gt; – it’s easy to connect through settings, MCP gives fast access to the code and line-by-line editing, and also use of different things of the IDE like file problem analysis.&lt;/li&gt;
&lt;li&gt;Mandatory clean code review using multi-agent approach to find gaps in work. It helps to reduce amount of problems in code before the review stage. I documented &lt;a href="https://protsenko.dev/ai-code-review-7-limitations-i-found-in-production/" rel="noopener noreferrer"&gt;seven AI code review limitations I found in production&lt;/a&gt; after running this workflow on real pull requests.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;To build the same process you have to install a few plugins through&amp;nbsp;&lt;code&gt;claude&lt;/code&gt;&amp;nbsp;-&amp;gt;&amp;nbsp;&lt;code&gt;plugins&lt;/code&gt;:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;a href="https://github.com/obra/superpowers" rel="noopener noreferrer"&gt;superpowers&lt;/a&gt;&amp;nbsp;– framework for working in spec-driven way, there’s a link to the repository with detailed skill descriptions.&lt;/li&gt;
&lt;li&gt;
&lt;code&gt;github&lt;/code&gt;&amp;nbsp;– to get information about comments from GitHub and reviewing pull requests.&lt;/li&gt;
&lt;li&gt;
&lt;a href="https://github.com/anthropics/claude-code/tree/main/plugins/pr-review-toolkit" rel="noopener noreferrer"&gt;pr-review-toolkit&lt;/a&gt;&amp;nbsp;– for multi-agent review.&lt;/li&gt;
&lt;/ul&gt;

&lt;h2&gt;
  
  
  My AI-driven development workflow
&lt;/h2&gt;

&lt;p&gt;Here is an example how I’m uniting all of this staff into my development workflow&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;Ask Claude: Let’s write a plan for feature: deep explanation of feature using brainstorming and writing-plans skills. Plan for implementation should be based on test-driven-development.&lt;/li&gt;
&lt;li&gt;Then comes the work with clarifications on the task and identifying different approaches, as a result you get a work plan you can execute using executing-plans. Such skill performs work step by step, validates at each stage and requests code review from itself.&lt;/li&gt;
&lt;li&gt;When the work is done – I check the code myself, dive in and edit when needed. Need for editing appears often even after long preparation.&lt;/li&gt;
&lt;li&gt;Ask Claude: Perform code review using pr review toolkit, then several different agents run with their own responsibility and at the output their results are combined to have less noise.&lt;/li&gt;
&lt;li&gt;As a result of code review, if there are any corner cases or obvious problems – I ask to write tests to reproduce them to understand the problem and fix it based on TDD methodology.&lt;/li&gt;
&lt;li&gt;The final step (for AI work) and intermediate step can be running the /simplify skill (part of review toolkit) so a separate agent checks what can be reused and reuses it. It helps to reduce code complexity and leads to proper reusing of functions instead of reinventing the wheel.&lt;/li&gt;
&lt;li&gt;Run deterministic guardrails for projects where they exist (highly recommend to setup), do manual testing of functionality, walk through the code and push if everything is ok.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;This process takes more time (and tokens) than just asking AI to roll out some changes, but gives a predictable result matching expectations and most importantly – reproducible and maintainable one.&lt;/p&gt;

&lt;h2&gt;
  
  
  Keep in mind about AI-driven development
&lt;/h2&gt;

&lt;h3&gt;
  
  
  Context size
&lt;/h3&gt;

&lt;p&gt;Context size – don’t use models with 1M context, firstly it’s very expensive after 100k tokens, and just not needed for our tasks.&lt;/p&gt;

&lt;p&gt;Keep the context small – call&amp;nbsp;&lt;code&gt;/compact&lt;/code&gt;&amp;nbsp;or create a new session&amp;nbsp;&lt;code&gt;/new&lt;/code&gt;, also for noisy tasks use&amp;nbsp;&lt;code&gt;subagent&lt;/code&gt;&amp;nbsp;– they have their own context and the execution result can be received in the current chat without noise. Transformers underlying LLMs make emphasis on the beginning and the end of context while the middle suffers consistently.&lt;/p&gt;

&lt;p&gt;This context problem also appears during review: &lt;a href="https://protsenko.dev/ai-code-review-7-limitations-i-found-in-production/#h-2-large-pull-requests-weaken-ai-code-review" rel="noopener noreferrer"&gt;large pull requests weaken AI code review&lt;/a&gt; in my production workflow.&lt;/p&gt;

&lt;p&gt;Important: Don’t add plans and specifications to git, keep them for yourself, otherwise AI context will be filled with things irrelevant to the current task. I prefer to store them from time to time and clean once a week.&lt;/p&gt;

&lt;h3&gt;
  
  
  AI will try to trick you
&lt;/h3&gt;

&lt;p&gt;AI will try to bypass tests and guardrails – you see &lt;code&gt;@Suppress&lt;/code&gt; in the code – means AI couldn’t solve something and just decided to turn off the check. Sometimes it’s actually needed but it’s rare. If there’s a suppress – don’t be lazy, solve the problem, and only when it doesn’t work out – leave the suppress with your comment.&lt;/p&gt;

&lt;p&gt;Remember: what matters is not the speed but the quality of the solution unless explicitly stated otherwise, every problem in the codebase will be multiplied too. AI-driven development is not an accelerator to reach goals, but a multiplier of the result, if the results are consistently bad – results will be worse over time.&lt;/p&gt;

&lt;h2&gt;
  
  
  Kotlin Guard Rails for AI-Driven Development
&lt;/h2&gt;

&lt;p&gt;Step 7 above says “run deterministic guardrails” – let me show you what that actually means in practice. You have to care about your codebase. Here is my recipe for maintaining the Kotlin codebase to reduce bugs at scale.&lt;/p&gt;

&lt;p&gt;These days, generated code appears in the codebase, but recent research shows AI-driven development can lead to bloating your codebase with duplicates and bugs even faster than before. Even though smell code has always been a problem, it’s now widespread.&lt;/p&gt;

&lt;p&gt;Each codebase should have guardrails, and it should always provide faster feedback than a human agent or a real dev, and better. It could be started by pre-commit checks or CI runs, or even together. Here is my setup for reducing smelly code.&lt;/p&gt;

&lt;h3&gt;
  
  
  Detekt
&lt;/h3&gt;

&lt;p&gt;&lt;a href="https://detekt.dev" rel="noopener noreferrer"&gt;Detekt&lt;/a&gt; is a static checker for Kotlin projects. It has a rich rule set that covers various aspects of the Kotlin language. It covers many different problems, but needs a small setup to choose not the default rules or adjust them so they are not too noisy.&lt;/p&gt;

&lt;h3&gt;
  
  
  Kover
&lt;/h3&gt;

&lt;p&gt;&lt;a href="https://github.com/Kotlin/kotlinx-kover" rel="noopener noreferrer"&gt;Kover&lt;/a&gt; for verification coverage. Maintainable code starts from unit tests, if you have them – you could sleep better knowing if something will be changed, unit tests highlighted. Yes, it depends on how you write tests, and even tests need validation, but it’s better to have them than not. Kover helps you get the test coverage percentage and fails if it exceeds the minimum threshold.&lt;/p&gt;

&lt;h3&gt;
  
  
  PMD CPD
&lt;/h3&gt;

&lt;p&gt;&lt;a href="https://pmd.github.io/pmd/pmd_userdocs_cpd.html" rel="noopener noreferrer"&gt;PMD CPD&lt;/a&gt; – relatively new integration that I started using, which needs to find duplicated code. It’s a very good tool because it helps you find duplicated code. When I configured it, I found more than 20 duplicates in a relatively new project, which was due to the AI-agent code generation. Even after code review, duplicates appear in the codebase.&lt;/p&gt;

&lt;h3&gt;
  
  
  Konsist
&lt;/h3&gt;

&lt;p&gt;&lt;a href="https://docs.konsist.lemonappdev.com" rel="noopener noreferrer"&gt;Konsist&lt;/a&gt; – one more tool that I started using a few weeks ago. Konsist provides a way to write architecture tests, and this is so awesome. Developers or AI agents often miss some different parts of the architecture. Previously, it was caught during review, but why focus on it if you can automate? For example, with it, you can write dozens of tests for your project structure, making sure nobody can violate it. Are you tired of Spring repositories in controllers? No problem, you write an arch test, and it runs as a common unit test. Last month, I built an arch rule set for Spring Boot Best Practices and will soon share it publicly.&lt;/p&gt;

&lt;p&gt;Konsist is required some time to configure, I did set of rules for Spring Boot projects covered different aspects of using Spring Boot powered by its Best Practices. You could read how to install this rule set from GitHub – &lt;a href="https://github.com/NordCoderd/spring-boot-code-guard" rel="noopener noreferrer"&gt;Spring Boot Code Guard&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;As example, using Spring Data JPA with Kotlin have some nuances, like you shouldn’t use &lt;code&gt;data class together with&lt;/code&gt; entity classes, that rule will look like this, this is example from Spring Boot Code Guard:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight kotlin"&gt;&lt;code&gt;    &lt;span class="cm"&gt;/**
     * Rule: @Entity classes should not be data classes.
     * Data classes are incompatible with JPA entities due to:
     * - Final by default (prevents lazy loading proxies)
     * - Structural equality in equals/hashCode (breaks entity identity)
     * - Immutability assumptions (conflicts with JPA state management)
     */&lt;/span&gt;
    &lt;span class="kd"&gt;val&lt;/span&gt; &lt;span class="py"&gt;noDataClassEntityRule&lt;/span&gt; &lt;span class="p"&gt;=&lt;/span&gt;
        &lt;span class="kd"&gt;object&lt;/span&gt; &lt;span class="err"&gt;: &lt;/span&gt;&lt;span class="nc"&gt;SpringBootRule&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
            &lt;span class="k"&gt;override&lt;/span&gt; &lt;span class="kd"&gt;val&lt;/span&gt; &lt;span class="py"&gt;description&lt;/span&gt; &lt;span class="p"&gt;=&lt;/span&gt; &lt;span class="s"&gt;"@Entity classes should not be data classes"&lt;/span&gt;
            &lt;span class="k"&gt;override&lt;/span&gt; &lt;span class="kd"&gt;val&lt;/span&gt; &lt;span class="py"&gt;suppressKey&lt;/span&gt; &lt;span class="p"&gt;=&lt;/span&gt; &lt;span class="s"&gt;"CodeGuard:noDataClassEntity"&lt;/span&gt;

            &lt;span class="k"&gt;override&lt;/span&gt; &lt;span class="k"&gt;fun&lt;/span&gt; &lt;span class="nf"&gt;verify&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;scope&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="nc"&gt;KoScope&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
                &lt;span class="n"&gt;scope&lt;/span&gt;
                    &lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;notSuppressedClasses&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;suppressKey&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
                    &lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;withAnnotationNamed&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nc"&gt;SpringAnnotations&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;entityAnnotations&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
                    &lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;filter&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt; &lt;span class="n"&gt;it&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;hasModifier&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nc"&gt;KoModifier&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nc"&gt;DATA&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="p"&gt;}&lt;/span&gt;
                    &lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;also&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt; &lt;span class="n"&gt;violations&lt;/span&gt; &lt;span class="p"&gt;-&amp;gt;&lt;/span&gt;
                        &lt;span class="k"&gt;if&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;violations&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;isNotEmpty&lt;/span&gt;&lt;span class="p"&gt;())&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
                            &lt;span class="kd"&gt;val&lt;/span&gt; &lt;span class="py"&gt;violatingClasses&lt;/span&gt; &lt;span class="p"&gt;=&lt;/span&gt; &lt;span class="n"&gt;violations&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;joinToString&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s"&gt;", "&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt; &lt;span class="n"&gt;it&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;name&lt;/span&gt; &lt;span class="p"&gt;}&lt;/span&gt;
                            &lt;span class="k"&gt;throw&lt;/span&gt; &lt;span class="nc"&gt;AssertionError&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;
                                &lt;span class="s"&gt;"Data classes should not be used as @Entity: $violatingClasses. "&lt;/span&gt; &lt;span class="p"&gt;+&lt;/span&gt;
                                    &lt;span class="s"&gt;"Data classes are incompatible with JPA due to their final nature, "&lt;/span&gt; &lt;span class="p"&gt;+&lt;/span&gt;
                                    &lt;span class="s"&gt;"structural equality, and immutability assumptions."&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
                            &lt;span class="p"&gt;)&lt;/span&gt;
                        &lt;span class="p"&gt;}&lt;/span&gt;
                    &lt;span class="p"&gt;}&lt;/span&gt;
            &lt;span class="p"&gt;}&lt;/span&gt;
        &lt;span class="p"&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h3&gt;
  
  
  Kotlin compiler
&lt;/h3&gt;

&lt;p&gt;Kotlin compiler – it highlights different problems that appeared in your project. By default, they don’t fail the whole process, so you have to activate it explicitly.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight kotlin"&gt;&lt;code&gt;&lt;span class="k"&gt;import&lt;/span&gt; &lt;span class="nn"&gt;org.jetbrains.kotlin.gradle.tasks.KotlinCompile&lt;/span&gt;

&lt;span class="n"&gt;tasks&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;withType&lt;/span&gt;&lt;span class="p"&gt;&amp;lt;&lt;/span&gt;&lt;span class="nc"&gt;KotlinCompile&lt;/span&gt;&lt;span class="p"&gt;&amp;gt;().&lt;/span&gt;&lt;span class="nf"&gt;configureEach&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
    &lt;span class="nf"&gt;compilerOptions&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
        &lt;span class="n"&gt;allWarningsAsErrors&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="k"&gt;set&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="k"&gt;true&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
    &lt;span class="p"&gt;}&lt;/span&gt;
&lt;span class="p"&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h3&gt;
  
  
  How to use them together
&lt;/h3&gt;

&lt;p&gt;My baseline is to have all four tools as one Gradle task that will:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Run Detekt&lt;/li&gt;
&lt;li&gt;Run all tests and check coverage&lt;/li&gt;
&lt;li&gt;Run the duplication detector to highlight problems&lt;/li&gt;
&lt;li&gt;Run architecture tests Spring Boot projects&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Finally it could be looks like this, in this example I intentiona&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight groovy"&gt;&lt;code&gt;&lt;span class="n"&gt;tasks&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;register&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="s2"&gt;"allChecks"&lt;/span&gt;&lt;span class="o"&gt;)&lt;/span&gt; &lt;span class="o"&gt;{&lt;/span&gt;
    &lt;span class="n"&gt;dependsOn&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="s2"&gt;"clean"&lt;/span&gt;&lt;span class="o"&gt;,&lt;/span&gt; &lt;span class="s2"&gt;"test"&lt;/span&gt;&lt;span class="o"&gt;,&lt;/span&gt; &lt;span class="s2"&gt;"cpdCheck"&lt;/span&gt;&lt;span class="o"&gt;,&lt;/span&gt; &lt;span class="s2"&gt;"detekt"&lt;/span&gt;&lt;span class="o"&gt;,&lt;/span&gt; &lt;span class="s2"&gt;"koverVerify"&lt;/span&gt;&lt;span class="o"&gt;)&lt;/span&gt;
    &lt;span class="n"&gt;description&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="s2"&gt;"Runs tests, Detekt, and Kover verification"&lt;/span&gt;
    &lt;span class="n"&gt;group&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="s2"&gt;"verification"&lt;/span&gt;
&lt;span class="o"&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;This task runs after the feature is finished. It runs automatically in CI and during AI agents development cycle as requirement. It helps a lot because of the short feedback on code changes – exactly what AI-driven development needs to stay maintainable at scale.&lt;/p&gt;

&lt;h2&gt;
  
  
  At the end
&lt;/h2&gt;

&lt;p&gt;More than year ago I posted on topic – &lt;a href="https://protsenko.dev/2025/04/14/ai-will-take-my-job-but-not-today/" rel="noopener noreferrer"&gt;AI Will Take My Job, But Not Today&lt;/a&gt;, but nowadays I changed my mind, it will drastically change my job, and changed already.&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;&lt;strong&gt;Found this useful?&lt;/strong&gt; Follow me on social media to stay updated.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://t.me/protsenko_dev" rel="noopener noreferrer"&gt;Telegram&lt;/a&gt; · &lt;a href="https://www.linkedin.com/in/protsenkodev/" rel="noopener noreferrer"&gt;LinkedIn&lt;/a&gt;&lt;/p&gt;
&lt;/blockquote&gt;

</description>
      <category>ai</category>
      <category>tdd</category>
      <category>productivity</category>
      <category>programming</category>
    </item>
    <item>
      <title>AI Code Review: 7 Limitations I Found in Production</title>
      <dc:creator>Dmitry Protsenko</dc:creator>
      <pubDate>Thu, 12 Nov 2026 15:00:00 +0000</pubDate>
      <link>https://dev.to/protsenko/ai-code-review-7-limitations-i-found-in-production-2ikh</link>
      <guid>https://dev.to/protsenko/ai-code-review-7-limitations-i-found-in-production-2ikh</guid>
      <description>&lt;p&gt;After two months of running AI code review on real pull requests, I found seven recurring limits: unverified fixes, weaker reviews on large PRs, anchoring on detailed specs, softer repeat passes, instruction overload, inconsistent rule enforcement, and missing intent. Research on code generation and long-context LLMs explains parts of this pattern, but not the whole pipeline.&lt;/p&gt;

&lt;p&gt;AI review still feels like a magic creature. On one side it catches bugs. On the other it makes things worse and hands you false confidence that everything is fine. The second one wins most days, in my experience.&lt;/p&gt;

&lt;p&gt;It runs on the&amp;nbsp;&lt;code&gt;pr-review-toolkit&lt;/code&gt;&amp;nbsp;plus a set of custom skills I built from the problems I keep seeing in real projects during code review. Those agents and skills feed a pipeline, and the pipeline is not small. Every agent gets its own clean context. The GitHub Action that drives it has turned into a heavy orchestrator, and it needs constant adaptation as new failure modes show up. I documented the complete setup in my &lt;a href="https://protsenko.dev/ai-driven-development-workflow-guard-rails/" rel="noopener noreferrer"&gt;AI coding workflow with TDD, reviews, and guardrails&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;In short: AI code review works best as the first pass, not as approval. This is the role I trust LLM code review to play: surface obvious defects, then hand the change to a human reviewer who knows the system’s intent.&lt;/p&gt;

&lt;h2&gt;
  
  
  1. AI-suggested fixes are not verified fixes
&lt;/h2&gt;

&lt;p&gt;We had code suggestions on at the start. The AI would propose a patch right in the GitHub comment. It looked helpful. It was not. Developers are applied patches, then spent time undoing them.&lt;/p&gt;

&lt;p&gt;Specific code-generation evaluations show why an unverified patch is risky. One GitHub Copilot study generated implementations for 200 Java methods from 124,800 prompt variants;&amp;nbsp;&lt;a href="https://arxiv.org/abs/2402.08430" rel="noopener noreferrer"&gt;75% did not compile, 13% compiled but failed at least one available test, and 12% passed all tests&lt;/a&gt;. In a separate security benchmark, Veracode evaluated more than 100 models on 80 single-function tasks across four languages. It reported that&amp;nbsp;&lt;a href="https://www.veracode.com/blog/genai-code-security-report/" rel="noopener noreferrer"&gt;45% of samples failed security tests, with a 72% failure rate for the Java tasks&lt;/a&gt;. These studies measure code generation, not review, and their tasks do not reproduce our pull requests. They are still enough reason not to present a suggested patch as verified.&lt;/p&gt;

&lt;p&gt;Anthropic made a related design choice when it launched Code Review for Claude Code on March 9, 2026: focus on bugs, verify findings, and leave approval to a human. The company says&amp;nbsp;&lt;a href="https://claude.com/blog/code-review" rel="noopener noreferrer"&gt;less than 1% of findings in its internal use were marked incorrect&lt;/a&gt;. That is a self-reported dismissal metric, not an independent false-positive evaluation, but the product boundary is sensible. The AI may point at a problem. I do not let it hand over a fix and pretend the job is finished.&lt;/p&gt;

&lt;h2&gt;
  
  
  2. Large pull requests weaken AI code review
&lt;/h2&gt;

&lt;p&gt;This was the most consistent thing I saw. Small PR: sharp, on topic, catches real issues. Large PR: it forgets instructions, gets lazy, skips obvious problems, stops doing the code-agreement checks I asked for, and sometimes just leaves an LGTM for nothing.&lt;/p&gt;

&lt;p&gt;Chroma tested 18 models, including GPT-4.1, Claude 4, and Gemini 2.5, and found that&amp;nbsp;&lt;a href="https://www.trychroma.com/research/context-rot" rel="noopener noreferrer"&gt;performance became less reliable as input length grew across its controlled tasks&lt;/a&gt;. The older “Lost in the Middle” paper found that&amp;nbsp;&lt;a href="https://arxiv.org/abs/2307.03172" rel="noopener noreferrer"&gt;performance was often highest when relevant information appeared at the beginning or end of a long input and lower when it appeared in the middle&lt;/a&gt;. In the current NoLiMa paper,&amp;nbsp;&lt;a href="https://arxiv.org/abs/2502.05167" rel="noopener noreferrer"&gt;10 of 12 tested models scored at or below half of their short-context baseline at 32K tokens&lt;/a&gt;. None of these is a code-review benchmark, so they do not prove that a long diff causes the failures I see. They do show why a large advertised context window is not the same as reliable use of every token.&lt;/p&gt;

&lt;p&gt;I introduced size limits on pull requests. Not mainly because of the AI, but because I find a 1,000-line PR hard to review well as a human too. The AI just made that cost impossible to ignore.&lt;/p&gt;

&lt;h2&gt;
  
  
  3. Detailed specs can anchor an AI reviewer
&lt;/h2&gt;

&lt;p&gt;This one surprised me. Follow good spec-driven-development practice, attach the plan, the spec, and a long confident PR description, and the AI reviews worse. It starts trusting the code. It tilts toward “this looks well planned” and leaves an approval. A long, detailed description does the same thing.&lt;/p&gt;

&lt;p&gt;Anchoring bias is one plausible mechanism, but the evidence is indirect. A 2024 study found that&amp;nbsp;&lt;a href="https://arxiv.org/abs/2412.06593" rel="noopener noreferrer"&gt;answers from three GPT models shifted toward numerical hints, and explicit instructions to ignore expert anchors did not reliably remove the effect&lt;/a&gt;. The study tested numerical estimation, not code review or specifications. A polished spec may act as an anchor, but that is my hypothesis, not the paper’s finding.&lt;/p&gt;

&lt;p&gt;Sycophancy offers another possible explanation. Anthropic researchers found that&amp;nbsp;&lt;a href="https://arxiv.org/abs/2310.13548" rel="noopener noreferrer"&gt;five AI assistants exhibited sycophancy across four text-generation tasks, while humans and preference models sometimes preferred convincing sycophantic responses over correct ones&lt;/a&gt;. The authors say the behavior is likely driven in part by preference judgments. They did not test pull requests, so a confident description influencing a reviewer remains a reasonable concern, not a demonstrated causal chain.&lt;/p&gt;

&lt;h2&gt;
  
  
  4. Repeat AI review passes get softer
&lt;/h2&gt;

&lt;p&gt;I do not have a paper for this one, so I will flag it as my observation, not a fact. After the AI leaves a batch of comments, the next iteration is noticeably weaker. It skips obvious problems it would have caught on a clean pass. It acts like the job is already done. Why work more if you already found something?&lt;/p&gt;

&lt;p&gt;I can only reason about why. Each iteration carries the previous comments forward, which adds context and may contribute to the degradation from observation 2. My sycophancy explanation is even more speculative; none of the cited studies tests repeated review rounds. The effect is consistent in my setup, but I do not know its cause. I trust the second and third AI passes less than the first, and I make sure a human owns the later rounds.&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;&lt;strong&gt;Found this useful?&lt;/strong&gt; Follow me on social media to stay updated.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://t.me/protsenko_dev" rel="noopener noreferrer"&gt;Telegram&lt;/a&gt; · &lt;a href="https://www.linkedin.com/in/protsenkodev/" rel="noopener noreferrer"&gt;LinkedIn&lt;/a&gt;&lt;/p&gt;
&lt;/blockquote&gt;

&lt;h2&gt;
  
  
  5. More instructions do not guarantee better AI review
&lt;/h2&gt;

&lt;p&gt;In my pipeline, more context does not automatically help. Past a point, more rules, examples, and guidance make the results worse. The reviewer spends effort matching the checklist and misses problems outside it.&lt;/p&gt;

&lt;p&gt;The research supports a narrower claim.&amp;nbsp;&lt;a href="https://aclanthology.org/2025.acl-long.803/" rel="noopener noreferrer"&gt;LIFBench evaluated instruction following for 20 models across six context-length intervals&lt;/a&gt;&amp;nbsp;and found that performance often declined as inputs grew, with substantial variation by model and task. It did not test code review or prove that a long checklist causes worse reasoning. Together with the broader long-context results, it is enough to treat prompt space as constrained. Past a certain size in my pipeline, adding instructions adds noise that competes with the code for the model’s attention.&lt;/p&gt;

&lt;h2&gt;
  
  
  6. AI code review applies best practices inconsistently
&lt;/h2&gt;

&lt;p&gt;The AI happily approves smelly code in runs. Even when I enforce a standard, sometimes it flags the violation and sometimes it does not. Same code, same rules, different verdict.&lt;/p&gt;

&lt;p&gt;That variability is measurable. One study configured five models with temperature zero and repeated eight benchmark tasks;&amp;nbsp;&lt;a href="https://arxiv.org/abs/2408.04667" rel="noopener noreferrer"&gt;none produced repeatable accuracy across every task, much less identical output strings&lt;/a&gt;. The authors explicitly say the underlying cause is unclear, so floating-point behavior, batching, or routing should not be presented as established explanations. “I told it the rule once” does not mean it will apply the rule every time.&lt;/p&gt;

&lt;p&gt;The broader code-quality picture raises a separate concern. GitClear analyzed 211 million changed lines from 2020 through 2024 and reported that, between 2021 and 2024,&amp;nbsp;&lt;a href="https://www.gitclear.com/ai_assistant_code_quality_2025_research" rel="noopener noreferrer"&gt;copy-pasted lines rose from 8.3% to 12.3% while lines associated with refactoring fell from about 25% to under 10%&lt;/a&gt;. This is a longitudinal, correlational study; it does not prove that AI caused the change. I treat it as a warning signal about review load and maintainability, not a verdict on every generator or reviewer.&lt;/p&gt;

&lt;h2&gt;
  
  
  7. AI code review cannot infer missing intent
&lt;/h2&gt;

&lt;p&gt;Add a new field to the database, and the AI nods. It has no idea why you did it. It cannot argue that the field is redundant, or that it breaks an invariant somewhere it cannot see, because it never learned your intent. It accepts the change and moves on.&lt;/p&gt;

&lt;p&gt;This is partly an input-boundary problem. “Diff-only” no longer describes every AI reviewer: Anthropic reports that its current system can&amp;nbsp;&lt;a href="https://claude.com/blog/code-review" rel="noopener noreferrer"&gt;surface a pre-existing bug in code adjacent to the pull request&lt;/a&gt;. My pipeline can inspect the repository too. It still cannot see a schema, API contract, or type definition in another service unless I expose it, and it cannot recover intent that exists only in someone’s head or in a private conversation. A reviewer cannot evaluate a constraint it never receives.&lt;/p&gt;

&lt;h2&gt;
  
  
  How AI code review works best
&lt;/h2&gt;

&lt;p&gt;The perfect AI review does not exist. AI review is a tool with measured limits. Anchoring, sycophancy, long-context degradation, and non-determinism all appear in the research, but none of the cited studies proves that every code-review failure is immutable or architectural. Better context, prompting, tools, and verification can reduce some failures. I do not assume configuration will eliminate them.&lt;/p&gt;

&lt;p&gt;The judgment of the human reviewer matters more now, not less. Do not replace classic code review with AI review. The worst outcome I can picture is AI-written code reviewed only by AI: an uncontrollable slop generation factory, two machines nodding at each other while nobody checks the assumptions.&lt;/p&gt;

&lt;p&gt;What works is treating AI review as the first cheap pass that clears obvious noise before a human spends real attention. Keep PRs small. Keep auto-fixes off. Do not hand it your spec as gospel. Keep a person on the late rounds. And keep adapting the pipeline, because the failure modes move.&lt;/p&gt;

&lt;p&gt;Adoption is a continuous process. Improvement depends on staying patient, careful, and curious about where it breaks. I will ask you what I keep asking myself: where has AI review actually saved you, and where did it quietly hand you false confidence?&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;&lt;strong&gt;Found this useful?&lt;/strong&gt; Follow me on social media to stay updated.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://t.me/protsenko_dev" rel="noopener noreferrer"&gt;Telegram&lt;/a&gt; · &lt;a href="https://www.linkedin.com/in/protsenkodev/" rel="noopener noreferrer"&gt;LinkedIn&lt;/a&gt;&lt;/p&gt;
&lt;/blockquote&gt;

</description>
      <category>ai</category>
      <category>codereview</category>
      <category>programming</category>
      <category>productivity</category>
    </item>
    <item>
      <title>Analyze Docker &amp; Kubernetes files with Qodana</title>
      <dc:creator>Dmitry Protsenko</dc:creator>
      <pubDate>Wed, 11 Nov 2026 15:00:00 +0000</pubDate>
      <link>https://dev.to/protsenko/analyze-docker-kubernetes-files-with-qodana-4a97</link>
      <guid>https://dev.to/protsenko/analyze-docker-kubernetes-files-with-qodana-4a97</guid>
      <description>&lt;p&gt;Hi! In this article, I’ll cover the interesting tool Qodana and how you could use it in CI/CD processes to scan your Docker and Kubernetes files with my &lt;a href="https://plugins.jetbrains.com/plugin/25413-cloud-iac-security" rel="noopener noreferrer"&gt;Cloud Security plugin&lt;/a&gt; for JetBrains IDEs.&lt;/p&gt;

&lt;h2&gt;
  
  
  Table of contents
&lt;/h2&gt;

&lt;ul&gt;
&lt;li&gt;What is Qodana?&lt;/li&gt;
&lt;li&gt;
Using Qodana for Code Analysis

&lt;ul&gt;
&lt;li&gt;Running Qodana in the IDE&lt;/li&gt;
&lt;li&gt;Running Qodana via Command-Line or Docker&lt;/li&gt;
&lt;li&gt;Cloud (IaC) Security Plugin for JetBrains IDEs&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;li&gt;Integrating Qodana with the Cloud Security Plugin&lt;/li&gt;
&lt;li&gt;Configuration of CI/CD for Qodana&lt;/li&gt;
&lt;li&gt;At the end&lt;/li&gt;
&lt;/ul&gt;

&lt;h2&gt;
  
  
  What is Qodana?
&lt;/h2&gt;

&lt;p&gt;The &lt;a href="https://www.jetbrains.com/qodana/" rel="noopener noreferrer"&gt;Qodana&lt;/a&gt; is JetBrains’s static code analysis and code quality platform, built on the same inspection engine as JetBrains IDEs. It brings the smart code inspections from the IDE directly into your CI/CD processes.&lt;/p&gt;

&lt;p&gt;In other words, Qodana runs the familiar IntelliJ IDEA/PhpStorm/WebStorm inspections in an automated manner to detect bugs, security vulnerabilities, and code quality issues in your project.&lt;/p&gt;

&lt;p&gt;My Docker and Kubernetes scanner for JetBrains IDE utilizes the same IntelliJ platform as Qodana’s, allowing me to easily integrate my own inspections and run them in the CLI.&lt;/p&gt;

&lt;h2&gt;
  
  
  Using Qodana for Code Analysis
&lt;/h2&gt;

&lt;p&gt;Before showing an example of how to scan Docker and Kubernetes files with Qodana, I’d like to explain typical ways in which you could analyze your code with Qodana.&lt;/p&gt;

&lt;h3&gt;
  
  
  Running Qodana in the IDE
&lt;/h3&gt;

&lt;p&gt;The Qodana is bundled into JetBrains IDEs as a &lt;a href="https://plugins.jetbrains.com/search?excludeTags=internal&amp;amp;products=idea&amp;amp;search=Qodana" rel="noopener noreferrer"&gt;plugin(s)&lt;/a&gt;. You can run a Qodana analysis from inside the IDE to get an overview of issues.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2Fhi54cew0dbhjl7kmeklq.webp" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2Fhi54cew0dbhjl7kmeklq.webp" alt="Opening the Qodana tool window inside IntelliJ IDEA" width="800" height="589"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;This allows you to experiment with Qodana locally – a Qodana tab in the IDE displays the analysis results, and you can view an HTML report or connect to the Qodana Cloud. Running Qodana in an IDE doesn’t require a separate license and helps you ensure that the CI checks will match your local findings.&lt;/p&gt;

&lt;h3&gt;
  
  
  Running Qodana via Command-Line or Docker
&lt;/h3&gt;

&lt;p&gt;Qodana provides a CLI (&lt;code&gt;qodana&lt;/code&gt; command, which essentially orchestrates the appropriate Docker container to run the analysis. You can easily install the Qodana CLI using Homebrew and other package managers. For more information, refer to their &lt;a href="https://github.com/JetBrains/qodana-cli?tab=readme-ov-file#Installation" rel="noopener noreferrer"&gt;documentation&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;Also, you could simply use &lt;code&gt;docker run&lt;/code&gt; it manually. For example, to scan a project with Qodana, you might run:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight shell"&gt;&lt;code&gt;docker pull jetbrains/qodana-jvm-community:latest
docker run &lt;span class="nt"&gt;--rm&lt;/span&gt; &lt;span class="nt"&gt;-v&lt;/span&gt; &lt;span class="si"&gt;$(&lt;/span&gt;&lt;span class="nb"&gt;pwd&lt;/span&gt;&lt;span class="si"&gt;)&lt;/span&gt;:/data/project/ jetbrains/qodana-jvm-community:latest
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;This would run the Qodana analysis on the current directory (mounted as &lt;code&gt;/data/project&lt;/code&gt; inside the container). By default, results are saved to an output folder (or can be viewed in the generated HTML report).&lt;/p&gt;

&lt;p&gt;This feature will enable us to scan Docker and Kubernetes files in CI/CD using a plugin.&lt;/p&gt;

&lt;h3&gt;
  
  
  Cloud (IaC) Security Plugin for JetBrains IDEs
&lt;/h3&gt;

&lt;p&gt;Let me tell you a bit about my plugin. It is an open-source plugin that adds security scanning for Docker and Kubernetes configuration files. (I mentioned this multiple times in the article, sorry for the repetition)&lt;/p&gt;

&lt;p&gt;The plugin performs real-time inspections of your infrastructure-as-code (IaC) files (like Dockerfiles, Docker Compose files, and Kubernetes YAML manifests) with 50+ rules inspired by industry best practices.&lt;/p&gt;

&lt;p&gt;If you are interested in &lt;a href="https://protsenko.dev/docker-best-practices-to-secure-and-optimize-your-containers/" rel="noopener noreferrer"&gt;Docker Security Best Practices&lt;/a&gt; or &lt;a href="https://protsenko.dev/kubernetes-security-top-12-best-practices-to-protect-your-cluster/" rel="noopener noreferrer"&gt;Kubernetes&lt;/a&gt;, click on those links. Two of these articles cover problems that my plugin could highlight. Additionally, each problem has a &lt;a href="https://protsenko.dev/infrastructure-security/" rel="noopener noreferrer"&gt;dedicated page in the documentation&lt;/a&gt; for those who want more examples.&lt;/p&gt;

&lt;h2&gt;
  
  
  Integrating Qodana with the Cloud Security Plugin
&lt;/h2&gt;

&lt;p&gt;Now that I described briefly the functionality of Qodana (our analyzer) and the Cloud (IaC) Security plugin (which knows how to scan Docker/Kubernetes files), the goal is to use them together: i.e., run Qodana in headless mode to scan our code, including any Docker and K8s manifest checks from the plugin.&lt;/p&gt;

&lt;p&gt;How to add the plugin to Qodana: Qodana can load additional IntelliJ plugins during analysis. JetBrains provides a simple way to do this via a configuration file. In the root of your project, you can create a &lt;code&gt;qodana.yaml&lt;/code&gt; configuration (or update your existing one) to include the Cloud Security plugin from JetBrains Marketplace.&lt;/p&gt;

&lt;p&gt;For example, you could add the following to your Qodana config:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight yaml"&gt;&lt;code&gt;&lt;span class="na"&gt;version&lt;/span&gt;&lt;span class="pi"&gt;:&lt;/span&gt; &lt;span class="s2"&gt;"&lt;/span&gt;&lt;span class="s"&gt;1.0"&lt;/span&gt;

&lt;span class="na"&gt;profile&lt;/span&gt;&lt;span class="pi"&gt;:&lt;/span&gt;
  &lt;span class="na"&gt;name&lt;/span&gt;&lt;span class="pi"&gt;:&lt;/span&gt; &lt;span class="s"&gt;qodana.recommended&lt;/span&gt;

&lt;span class="na"&gt;plugins&lt;/span&gt;&lt;span class="pi"&gt;:&lt;/span&gt;
  &lt;span class="pi"&gt;-&lt;/span&gt; &lt;span class="na"&gt;id&lt;/span&gt;&lt;span class="pi"&gt;:&lt;/span&gt; &lt;span class="s"&gt;Docker&lt;/span&gt;
  &lt;span class="pi"&gt;-&lt;/span&gt; &lt;span class="na"&gt;id&lt;/span&gt;&lt;span class="pi"&gt;:&lt;/span&gt; &lt;span class="s"&gt;org.jetbrains.plugins.yaml&lt;/span&gt;
  &lt;span class="pi"&gt;-&lt;/span&gt; &lt;span class="na"&gt;id&lt;/span&gt;&lt;span class="pi"&gt;:&lt;/span&gt; &lt;span class="s"&gt;dev.protsenko.security-linter&lt;/span&gt;

&lt;span class="na"&gt;include&lt;/span&gt;&lt;span class="pi"&gt;:&lt;/span&gt;
  &lt;span class="c1"&gt;# docker-compose + k8s (YAML)&lt;/span&gt;
  &lt;span class="pi"&gt;-&lt;/span&gt; &lt;span class="na"&gt;name&lt;/span&gt;&lt;span class="pi"&gt;:&lt;/span&gt; &lt;span class="s"&gt;DockerCompose&lt;/span&gt;
  &lt;span class="pi"&gt;-&lt;/span&gt; &lt;span class="na"&gt;name&lt;/span&gt;&lt;span class="pi"&gt;:&lt;/span&gt; &lt;span class="s"&gt;NonRootContainer&lt;/span&gt;
  &lt;span class="pi"&gt;-&lt;/span&gt; &lt;span class="na"&gt;name&lt;/span&gt;&lt;span class="pi"&gt;:&lt;/span&gt; &lt;span class="s"&gt;InsecureCapabilities&lt;/span&gt;
  &lt;span class="pi"&gt;-&lt;/span&gt; &lt;span class="na"&gt;name&lt;/span&gt;&lt;span class="pi"&gt;:&lt;/span&gt; &lt;span class="s"&gt;HostNetworkPidIpc&lt;/span&gt;
  &lt;span class="pi"&gt;-&lt;/span&gt; &lt;span class="na"&gt;name&lt;/span&gt;&lt;span class="pi"&gt;:&lt;/span&gt; &lt;span class="s"&gt;PrivilegedContainers&lt;/span&gt;
  &lt;span class="pi"&gt;-&lt;/span&gt; &lt;span class="na"&gt;name&lt;/span&gt;&lt;span class="pi"&gt;:&lt;/span&gt; &lt;span class="s"&gt;HostPathVolumes&lt;/span&gt;
  &lt;span class="pi"&gt;-&lt;/span&gt; &lt;span class="na"&gt;name&lt;/span&gt;&lt;span class="pi"&gt;:&lt;/span&gt; &lt;span class="s"&gt;HostPorts&lt;/span&gt;
  &lt;span class="pi"&gt;-&lt;/span&gt; &lt;span class="na"&gt;name&lt;/span&gt;&lt;span class="pi"&gt;:&lt;/span&gt; &lt;span class="s"&gt;AppArmorOverride&lt;/span&gt;
  &lt;span class="pi"&gt;-&lt;/span&gt; &lt;span class="na"&gt;name&lt;/span&gt;&lt;span class="pi"&gt;:&lt;/span&gt; &lt;span class="s"&gt;SettingSELinux&lt;/span&gt;
  &lt;span class="pi"&gt;-&lt;/span&gt; &lt;span class="na"&gt;name&lt;/span&gt;&lt;span class="pi"&gt;:&lt;/span&gt; &lt;span class="s"&gt;InsecureProcMount&lt;/span&gt;
  &lt;span class="pi"&gt;-&lt;/span&gt; &lt;span class="na"&gt;name&lt;/span&gt;&lt;span class="pi"&gt;:&lt;/span&gt; &lt;span class="s"&gt;SeccompProfile&lt;/span&gt;
  &lt;span class="pi"&gt;-&lt;/span&gt; &lt;span class="na"&gt;name&lt;/span&gt;&lt;span class="pi"&gt;:&lt;/span&gt; &lt;span class="s"&gt;InsecureSysctls&lt;/span&gt;
  &lt;span class="pi"&gt;-&lt;/span&gt; &lt;span class="na"&gt;name&lt;/span&gt;&lt;span class="pi"&gt;:&lt;/span&gt; &lt;span class="s"&gt;DisallowedVolumeType&lt;/span&gt;

  &lt;span class="c1"&gt;# Dockerfile&lt;/span&gt;
  &lt;span class="pi"&gt;-&lt;/span&gt; &lt;span class="na"&gt;name&lt;/span&gt;&lt;span class="pi"&gt;:&lt;/span&gt; &lt;span class="s"&gt;DockerfileCmdAndEntrypoint&lt;/span&gt;
  &lt;span class="pi"&gt;-&lt;/span&gt; &lt;span class="na"&gt;name&lt;/span&gt;&lt;span class="pi"&gt;:&lt;/span&gt; &lt;span class="s"&gt;DockerfileCopyAndAdd&lt;/span&gt;
  &lt;span class="pi"&gt;-&lt;/span&gt; &lt;span class="na"&gt;name&lt;/span&gt;&lt;span class="pi"&gt;:&lt;/span&gt; &lt;span class="s"&gt;DockerFileEnv&lt;/span&gt;
  &lt;span class="pi"&gt;-&lt;/span&gt; &lt;span class="na"&gt;name&lt;/span&gt;&lt;span class="pi"&gt;:&lt;/span&gt; &lt;span class="s"&gt;DockerfileExpose&lt;/span&gt;
  &lt;span class="pi"&gt;-&lt;/span&gt; &lt;span class="na"&gt;name&lt;/span&gt;&lt;span class="pi"&gt;:&lt;/span&gt; &lt;span class="s"&gt;DockerfileFrom&lt;/span&gt;
  &lt;span class="pi"&gt;-&lt;/span&gt; &lt;span class="na"&gt;name&lt;/span&gt;&lt;span class="pi"&gt;:&lt;/span&gt; &lt;span class="s"&gt;DockerfileHealthCheck&lt;/span&gt;
  &lt;span class="pi"&gt;-&lt;/span&gt; &lt;span class="na"&gt;name&lt;/span&gt;&lt;span class="pi"&gt;:&lt;/span&gt; &lt;span class="s"&gt;DockerfileMaintainer&lt;/span&gt;
  &lt;span class="pi"&gt;-&lt;/span&gt; &lt;span class="na"&gt;name&lt;/span&gt;&lt;span class="pi"&gt;:&lt;/span&gt; &lt;span class="s"&gt;DockerfileRun&lt;/span&gt;
  &lt;span class="pi"&gt;-&lt;/span&gt; &lt;span class="na"&gt;name&lt;/span&gt;&lt;span class="pi"&gt;:&lt;/span&gt; &lt;span class="s"&gt;DockerfileUser&lt;/span&gt;
  &lt;span class="pi"&gt;-&lt;/span&gt; &lt;span class="na"&gt;name&lt;/span&gt;&lt;span class="pi"&gt;:&lt;/span&gt; &lt;span class="s"&gt;DockerfileWorkdir&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;With this configuration, you can enable my plugin to perform Docker and Kubernetes scanning in your project. From the IDE, it will appear as shown in the following screenshot.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2F46g387eynezysluo6j5l.webp" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2F46g387eynezysluo6j5l.webp" alt="Qodana results in the IDE with Docker and Kubernetes findings from the Cloud (IaC) Security plugin" width="800" height="575"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Via CLI, you’ll get something like this; that’s all (almost) you need to integrate Qodana into CI/CD processes.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2Ftm3f1d8v7b8gkud4ebj3.webp" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2Ftm3f1d8v7b8gkud4ebj3.webp" alt="Qodana CLI output with Docker and Kubernetes findings" width="800" height="388"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;h2&gt;
  
  
  Configuration of CI/CD for Qodana
&lt;/h2&gt;

&lt;p&gt;It’s actually easy. With the IDE and the Qodana plugin, you can configure CI/CD for various systems, including GitHub Actions, Jenkins, TeamCity, and others.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2Fsxty9efmnd9g5hqsjjo4.webp" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2Fsxty9efmnd9g5hqsjjo4.webp" alt="Qodana CI/CD setup options for GitHub Actions, Jenkins and TeamCity" width="800" height="407"&gt;&lt;/a&gt;&lt;br&gt;
&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2F2gkxv53vr2132c7n0k78.webp" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2F2gkxv53vr2132c7n0k78.webp" alt="GitHub Actions workflow configuration for running Qodana" width="800" height="817"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;So, the configuration for CI/CD is not complex, and I’ve no idea what I could describe here. Give it a try, and I think you’ll be pleased with this solution. Developers of Qodana have done great work in this field.&lt;/p&gt;

&lt;h2&gt;
  
  
  At the end
&lt;/h2&gt;

&lt;p&gt;By combining Qodana with the Cloud (IaC) Security plugin, you can perform comprehensive static analysis that includes both application code and Docker and Kubernetes configuration files.&lt;/p&gt;

&lt;p&gt;Qodana provides a platform for running inspections in a consistent and automated way, and the Cloud Security plugin contributes a rich set of DevSecOps rules (covering Docker best practices and Kubernetes security standards) to Qodana’s arsenal.&lt;/p&gt;

&lt;p&gt;If you enjoy my articles, please connect with me on &lt;a href="https://www.linkedin.com/in/protsenkodev/" rel="noopener noreferrer"&gt;LinkedIn&lt;/a&gt; to stay informed about new content. If you’re interested in IntelliJ IDEA plugin development, read my latest: &lt;a href="https://protsenko.dev/intellij-idea-plugin-development-what-have-i-learned/" rel="noopener noreferrer"&gt;IntelliJ IDEA Plugin Development: What Have I Learned&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;More in my &lt;a href="https://protsenko.dev/security/" rel="noopener noreferrer"&gt;container and supply chain security guides&lt;/a&gt;. Related: &lt;a href="https://protsenko.dev/docker-best-practices-to-secure-and-optimize-your-containers/" rel="noopener noreferrer"&gt;Dockerfile Best Practices: 29 Rules for Better Images&lt;/a&gt;.&lt;/strong&gt;&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;&lt;strong&gt;Found this useful?&lt;/strong&gt; Follow me on social media to stay updated.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://t.me/protsenko_dev" rel="noopener noreferrer"&gt;Telegram&lt;/a&gt; · &lt;a href="https://www.linkedin.com/in/protsenkodev/" rel="noopener noreferrer"&gt;LinkedIn&lt;/a&gt;&lt;/p&gt;
&lt;/blockquote&gt;

</description>
      <category>docker</category>
      <category>kubernetes</category>
      <category>devops</category>
      <category>security</category>
    </item>
    <item>
      <title>Spring AI RAG example: index source code with PgVector</title>
      <dc:creator>Dmitry Protsenko</dc:creator>
      <pubDate>Tue, 10 Nov 2026 15:00:00 +0000</pubDate>
      <link>https://dev.to/protsenko/spring-ai-rag-example-index-source-code-with-pgvector-p5l</link>
      <guid>https://dev.to/protsenko/spring-ai-rag-example-index-source-code-with-pgvector-p5l</guid>
      <description>&lt;p&gt;This Spring AI RAG example builds a source-code index with a Spring AI vector store backed by PgVector. It deduplicates files, splits them into embedding-sized chunks, and returns grounded answers with file citations taken from retrieval metadata.&lt;/p&gt;

&lt;p&gt;Think of it as a local&amp;nbsp;Context7-style index for the library sources your project actually uses, with indexing exposed over MCP. A model trained last year does not know the API you upgraded to last week.&lt;/p&gt;

&lt;p&gt;By the end, you will have a Spring AI RAG indexer for dependency sources and a chat client that answers from indexed code with file citations. Gradle downloads the source jars, the MCP tool builds the index, and&amp;nbsp;&lt;code&gt;/api/chat&lt;/code&gt;&amp;nbsp;asks questions against it. If an outside MCP agent also needs to search or ask, wrap&amp;nbsp;&lt;code&gt;CodeAssistantService.ask(...)&lt;/code&gt;&amp;nbsp;in a separate MCP tool.&lt;/p&gt;

&lt;h2&gt;
  
  
  Table of contents
&lt;/h2&gt;

&lt;ul&gt;
&lt;li&gt;How this Spring AI RAG example fits together&lt;/li&gt;
&lt;li&gt;
Deduplicate documents in the Spring AI vector store

&lt;ul&gt;
&lt;li&gt;Deduplication by document hash&lt;/li&gt;
&lt;li&gt;Deduplication by deterministic id (default upsert)&lt;/li&gt;
&lt;li&gt;Deduplication by deterministic id (via JdbcTemplate)&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;li&gt;
Chunk documents for Spring AI RAG retrieval

&lt;ul&gt;
&lt;li&gt;Nuances of tokenization and text splitting&lt;/li&gt;
&lt;li&gt;Splitting text by tokens configuration&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;li&gt;From index to answers: a grounded chat client&lt;/li&gt;
&lt;li&gt;How Spring AI QuestionAnswerAdvisor grounds a RAG prompt&lt;/li&gt;
&lt;li&gt;When the model invents file paths&lt;/li&gt;
&lt;li&gt;
Add file citations to a Spring AI RAG response

&lt;ul&gt;
&lt;li&gt;The client reply differs from the model’s message&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;li&gt;Where to go next with Spring AI RAG&lt;/li&gt;
&lt;/ul&gt;

&lt;h2&gt;
  
  
  How this Spring AI RAG example fits together
&lt;/h2&gt;

&lt;p&gt;The project from part one already has the pieces. It is a Spring Boot RAG application running Spring Boot 4.1 and Spring AI with PgVector. I added a Gradle task,&amp;nbsp;&lt;code&gt;downloadDependencySources&lt;/code&gt;, that resolves each runtime dependency’s source jar and unpacks it into&amp;nbsp;&lt;code&gt;sources/&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;The flow looks like this:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;Run&amp;nbsp;&lt;code&gt;downloadDependencySources&lt;/code&gt;&amp;nbsp;once to export and unpack your own dependency sources.&lt;/li&gt;
&lt;li&gt;An indexer walks&amp;nbsp;&lt;code&gt;sources/&lt;/code&gt;, splits each file into chunks, embeds those chunks, and stores them in pgvector.&lt;/li&gt;
&lt;li&gt;The&amp;nbsp;&lt;code&gt;index_sources&lt;/code&gt;&amp;nbsp;MCP tool builds the index, and the&amp;nbsp;&lt;code&gt;/api/chat&lt;/code&gt;&amp;nbsp;endpoint asks questions against it.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;The first index uses two small services:&amp;nbsp;&lt;code&gt;SourcesIndexerService&lt;/code&gt;&amp;nbsp;and&amp;nbsp;&lt;code&gt;SourcesQueryService&lt;/code&gt;. The MCP tool does not need a separate wrapper class; it lives as an annotated method on the indexer service.&lt;/p&gt;

&lt;h2&gt;
  
  
  Deduplicate documents in the Spring AI vector store
&lt;/h2&gt;

&lt;p&gt;Indexing has a problem: you will run it more than once. The app restarts. The source export task runs again. Or you change the embedding model and rebuild the index. If every run inserts the same files again, retrieval quality drops. Top-K results fill with duplicate source files. The database also grows without adding value.&lt;/p&gt;

&lt;p&gt;Spring AI does not give you one generic “deduplicate this” switch. The&amp;nbsp;&lt;code&gt;VectorStore&lt;/code&gt;&amp;nbsp;contract stays small by design. Deduplication belongs to your document identity model.&lt;/p&gt;

&lt;p&gt;Three options can help: hash checks, fixed ids with PgVector upsert, and a JDBC pre-check before embedding. This demo combines the last two. Fixed text ids keep rows stable. Checksum metadata detects changes.&amp;nbsp;&lt;code&gt;JdbcTemplate&lt;/code&gt;&amp;nbsp;skips unchanged files before the embedding call.&lt;/p&gt;

&lt;h3&gt;
  
  
  Deduplication by document hash
&lt;/h3&gt;

&lt;p&gt;The first version calculated a checksum for each file, stored that checksum as metadata, and asked the vector store whether a document with that checksum already existed.&lt;/p&gt;

&lt;p&gt;The query wrapped the same&amp;nbsp;&lt;code&gt;VectorStore&lt;/code&gt;. It ran a metadata-filtered search with an empty query,&amp;nbsp;&lt;code&gt;topK(1)&lt;/code&gt;, and a zero threshold.&lt;/p&gt;

&lt;p&gt;That version works across vector stores, but it hides a cost:&amp;nbsp;&lt;code&gt;similaritySearch(...)&lt;/code&gt;&amp;nbsp;still asks the embedding model for a query vector before PgVector can run SQL. For an indexer you run often, the dedupe check should not call the embedding model at all.&lt;/p&gt;

&lt;h3&gt;
  
  
  Deduplication by deterministic id (default upsert)
&lt;/h3&gt;

&lt;p&gt;The demo solution rests on fixed document identity. A&amp;nbsp;&lt;code&gt;Document&lt;/code&gt;&amp;nbsp;created with&amp;nbsp;&lt;code&gt;new Document(text, metadata)&lt;/code&gt;&amp;nbsp;gets a random id. Every re-index then creates a new row. A&amp;nbsp;&lt;code&gt;Document&lt;/code&gt;&amp;nbsp;created with&amp;nbsp;&lt;code&gt;new Document(id, text, metadata)&lt;/code&gt;&amp;nbsp;keeps the same id every time.&lt;/p&gt;

&lt;p&gt;For source files, the id should come from the file identity, not just the file content. Say you key on the checksum alone. Then two different files with identical content collapse into one document. In the demo I use a readable text id built from the library and the source path:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight java"&gt;&lt;code&gt;&lt;span class="kd"&gt;private&lt;/span&gt; &lt;span class="nc"&gt;String&lt;/span&gt; &lt;span class="nf"&gt;documentId&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="nc"&gt;String&lt;/span&gt; &lt;span class="n"&gt;library&lt;/span&gt;&lt;span class="o"&gt;,&lt;/span&gt; &lt;span class="nc"&gt;Path&lt;/span&gt; &lt;span class="n"&gt;relative&lt;/span&gt;&lt;span class="o"&gt;)&lt;/span&gt; &lt;span class="o"&gt;{&lt;/span&gt;
    &lt;span class="nc"&gt;String&lt;/span&gt; &lt;span class="n"&gt;sourcePath&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;relative&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;getNameCount&lt;/span&gt;&lt;span class="o"&gt;()&lt;/span&gt; &lt;span class="o"&gt;&amp;gt;&lt;/span&gt; &lt;span class="mi"&gt;1&lt;/span&gt;
            &lt;span class="o"&gt;?&lt;/span&gt; &lt;span class="n"&gt;relative&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;subpath&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;1&lt;/span&gt;&lt;span class="o"&gt;,&lt;/span&gt; &lt;span class="n"&gt;relative&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;getNameCount&lt;/span&gt;&lt;span class="o"&gt;()).&lt;/span&gt;&lt;span class="na"&gt;toString&lt;/span&gt;&lt;span class="o"&gt;()&lt;/span&gt;
            &lt;span class="o"&gt;:&lt;/span&gt; &lt;span class="n"&gt;relative&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;toString&lt;/span&gt;&lt;span class="o"&gt;();&lt;/span&gt;
    &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="n"&gt;library&lt;/span&gt; &lt;span class="o"&gt;+&lt;/span&gt; &lt;span class="s"&gt;"/"&lt;/span&gt; &lt;span class="o"&gt;+&lt;/span&gt; &lt;span class="n"&gt;sourcePath&lt;/span&gt;&lt;span class="o"&gt;;&lt;/span&gt;
&lt;span class="o"&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The current indexer uses that method to build the parent id before it splits a source file into chunks.&lt;/p&gt;

&lt;p&gt;The exact string format does not matter. The same source file must produce the same id on every run. If the file changes later, the id stays stable. The next run can then replace the content and embedding for that row.&lt;/p&gt;

&lt;p&gt;One PgVector detail matters here. This Spring AI PgVector example uses readable ids, but Spring AI’s PgVector store defaults to UUID ids. A readable id like&amp;nbsp;&lt;code&gt;library/path&lt;/code&gt;&amp;nbsp;needs a text id column:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight properties"&gt;&lt;code&gt;&lt;span class="py"&gt;spring.ai.vectorstore.pgvector.id-type&lt;/span&gt;&lt;span class="p"&gt;=&lt;/span&gt;&lt;span class="s"&gt;TEXT&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;If you keep the default UUID id type, use a deterministic UUID generator instead of a readable path id.&lt;/p&gt;

&lt;p&gt;Spring AI’s PgVector store inserts with&amp;nbsp;&lt;code&gt;ON CONFLICT (id) DO UPDATE&lt;/code&gt;, so fixed ids make repeat indexing update existing rows instead of piling up duplicates. Without chunking, fixed ids keep one row per source file. In the final chunked indexer, fixed chunk ids make repeat indexing update matching chunk rows.&lt;/p&gt;

&lt;p&gt;A fixed id alone does not skip embedding. Spring AI computes embeddings before the insert. The id protects the table from duplicate rows. It does not protect the embedding model from repeated work.&lt;/p&gt;

&lt;h3&gt;
  
  
  Deduplication by deterministic id (via JdbcTemplate)
&lt;/h3&gt;

&lt;p&gt;For true “do nothing” behavior on unchanged files, make the decision before&amp;nbsp;&lt;code&gt;vectorStore.add(...)&lt;/code&gt;. Spring AI’s PgVector store does not expose a switch from&amp;nbsp;&lt;code&gt;ON CONFLICT DO UPDATE&lt;/code&gt;&amp;nbsp;to&amp;nbsp;&lt;code&gt;ON CONFLICT DO NOTHING&lt;/code&gt;. By the time PgVector runs its insert, Spring AI has already calculated the embedding.&lt;/p&gt;

&lt;p&gt;The practical version uses a direct id-and-checksum lookup with&amp;nbsp;&lt;code&gt;JdbcTemplate&lt;/code&gt;. If the stored row has the same id and checksum, return before&amp;nbsp;&lt;code&gt;vectorStore.add(...)&lt;/code&gt;. If no row matches, or the checksum changed, call&amp;nbsp;&lt;code&gt;vectorStore.add(...)&lt;/code&gt;&amp;nbsp;and let PgVector upsert the row.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight java"&gt;&lt;code&gt;&lt;span class="nd"&gt;@Service&lt;/span&gt;
&lt;span class="nd"&gt;@RequiredArgsConstructor&lt;/span&gt;
&lt;span class="kd"&gt;public&lt;/span&gt; &lt;span class="kd"&gt;class&lt;/span&gt; &lt;span class="nc"&gt;SourcesQueryService&lt;/span&gt; &lt;span class="o"&gt;{&lt;/span&gt;
    &lt;span class="kd"&gt;private&lt;/span&gt; &lt;span class="kd"&gt;final&lt;/span&gt; &lt;span class="nc"&gt;JdbcTemplate&lt;/span&gt; &lt;span class="n"&gt;jdbcTemplate&lt;/span&gt;&lt;span class="o"&gt;;&lt;/span&gt;

    &lt;span class="kd"&gt;public&lt;/span&gt; &lt;span class="kt"&gt;boolean&lt;/span&gt; &lt;span class="nf"&gt;isDocumentStoredByIdAndCheckSum&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="nc"&gt;String&lt;/span&gt; &lt;span class="n"&gt;id&lt;/span&gt;&lt;span class="o"&gt;,&lt;/span&gt; &lt;span class="nc"&gt;Long&lt;/span&gt; &lt;span class="n"&gt;checkSum&lt;/span&gt;&lt;span class="o"&gt;)&lt;/span&gt; &lt;span class="o"&gt;{&lt;/span&gt;
        &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="nc"&gt;Boolean&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;TRUE&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;equals&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="n"&gt;jdbcTemplate&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;queryForObject&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="sh"&gt;"""
                select exists (
                    select 1
                    from public.vector_store
                    where id = ?
                      and metadata -&amp;gt;&amp;gt; 'checksum' = ?
                )
                """&lt;/span&gt;&lt;span class="o"&gt;,&lt;/span&gt; &lt;span class="nc"&gt;Boolean&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;class&lt;/span&gt;&lt;span class="o"&gt;,&lt;/span&gt; &lt;span class="n"&gt;id&lt;/span&gt;&lt;span class="o"&gt;,&lt;/span&gt; &lt;span class="n"&gt;checkSum&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;toString&lt;/span&gt;&lt;span class="o"&gt;()));&lt;/span&gt;
    &lt;span class="o"&gt;}&lt;/span&gt;
&lt;span class="o"&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Then the current indexer can skip unchanged files before it splits and embeds the source:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight java"&gt;&lt;code&gt;&lt;span class="nc"&gt;Long&lt;/span&gt; &lt;span class="n"&gt;checksum&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;crc32&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="n"&gt;file&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;toAbsolutePath&lt;/span&gt;&lt;span class="o"&gt;());&lt;/span&gt;
&lt;span class="nc"&gt;String&lt;/span&gt; &lt;span class="n"&gt;parentDocumentId&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;documentId&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="n"&gt;library&lt;/span&gt;&lt;span class="o"&gt;,&lt;/span&gt; &lt;span class="n"&gt;relative&lt;/span&gt;&lt;span class="o"&gt;);&lt;/span&gt;
&lt;span class="nc"&gt;String&lt;/span&gt; &lt;span class="n"&gt;firstChunkId&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;chunkId&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="n"&gt;parentDocumentId&lt;/span&gt;&lt;span class="o"&gt;,&lt;/span&gt; &lt;span class="mi"&gt;0&lt;/span&gt;&lt;span class="o"&gt;);&lt;/span&gt;

&lt;span class="k"&gt;if&lt;/span&gt; &lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="n"&gt;queryService&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;isDocumentStoredByIdAndCheckSum&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="n"&gt;firstChunkId&lt;/span&gt;&lt;span class="o"&gt;,&lt;/span&gt; &lt;span class="n"&gt;checksum&lt;/span&gt;&lt;span class="o"&gt;))&lt;/span&gt; &lt;span class="o"&gt;{&lt;/span&gt;
    &lt;span class="n"&gt;log&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;debug&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="s"&gt;"Source document already stored: {}"&lt;/span&gt;&lt;span class="o"&gt;,&lt;/span&gt; &lt;span class="n"&gt;relative&lt;/span&gt;&lt;span class="o"&gt;);&lt;/span&gt;
    &lt;span class="k"&gt;return&lt;/span&gt;&lt;span class="o"&gt;;&lt;/span&gt;
&lt;span class="o"&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;This trades portability for behavior this service needs. It depends on PgVector’s table and metadata layout:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;same id and same checksum: do nothing;&lt;/li&gt;
&lt;li&gt;same id and different checksum: embed and upsert;&lt;/li&gt;
&lt;li&gt;missing id: embed and insert.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;The&amp;nbsp;&lt;code&gt;id&lt;/code&gt;&amp;nbsp;lookup already uses PgVector’s primary key. Add metadata expression indexes only for queries that scan by checksum or parent metadata without a specific id.&lt;/p&gt;

&lt;p&gt;For the demo service, use this version: a cheap JdbcTemplate pre-check plus PgVector upsert for changed files.&lt;/p&gt;

&lt;p&gt;That tradeoff pays off. One SQL read can save one model call. In the chunked index, each row maps to one chunk: no duplicate rows and no repeated embedding call for unchanged files.&lt;/p&gt;

&lt;h2&gt;
  
  
  Chunk documents for Spring AI RAG retrieval
&lt;/h2&gt;

&lt;p&gt;Deduplication decides whether to store a document. Chunking decides the document shape.&lt;/p&gt;

&lt;p&gt;That boundary matters with source files. Spring AI’s default vector-store batch strategy counts tokens before embedding. It can batch many small documents, but it will not split one oversize file. If a file exceeds the embedding model’s limit,&amp;nbsp;&lt;code&gt;vectorStore.add(...)&lt;/code&gt;&amp;nbsp;throws before the file reaches Postgres.&lt;/p&gt;

&lt;p&gt;You will see this failure:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;java.lang.IllegalArgumentException: Tokens in a single document exceeds the maximum number of allowed input tokens
    at org.springframework.ai.embedding.TokenCountBatchingStrategy.batch(TokenCountBatchingStrategy.java:151) ~[spring-ai-model-2.0.0-RC2.jar:2.0.0-RC2]
    at org.springframework.ai.embedding.EmbeddingModel.embed(EmbeddingModel.java:106) ~[spring-ai-model-2.0.0-RC2.jar:2.0.0-RC2]
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;That error means the batching strategy rejected one&amp;nbsp;&lt;code&gt;Document&lt;/code&gt;. A bigger batch size will not help. The document itself has to shrink.&lt;/p&gt;

&lt;p&gt;The Spring AI ETL pipeline has a tool for this job:&amp;nbsp;&lt;code&gt;TokenTextSplitter&lt;/code&gt;. It implements&amp;nbsp;&lt;code&gt;DocumentTransformer&lt;/code&gt;. It takes a list of&amp;nbsp;&lt;code&gt;Document&lt;/code&gt;&amp;nbsp;objects and returns a new list of smaller&amp;nbsp;&lt;code&gt;Document&lt;/code&gt;&amp;nbsp;objects. The split runs before&amp;nbsp;&lt;code&gt;vectorStore.add(...)&lt;/code&gt;, so the embedding model sees chunks instead of the original large file.&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;&lt;strong&gt;Found this useful?&lt;/strong&gt; Follow me on social media to stay updated.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://t.me/protsenko_dev" rel="noopener noreferrer"&gt;Telegram&lt;/a&gt; · &lt;a href="https://www.linkedin.com/in/protsenkodev/" rel="noopener noreferrer"&gt;LinkedIn&lt;/a&gt;&lt;/p&gt;
&lt;/blockquote&gt;

&lt;h3&gt;
  
  
  Nuances of tokenization and text splitting
&lt;/h3&gt;

&lt;p&gt;&lt;code&gt;TokenTextSplitter&lt;/code&gt;&amp;nbsp;runs locally. It does not call the embedding model or send text to an AI server. It uses&amp;nbsp;&lt;code&gt;jtokkit&lt;/code&gt;&amp;nbsp;to map text to token ids, takes up to&amp;nbsp;&lt;code&gt;chunkSize&lt;/code&gt;&amp;nbsp;tokens, decodes that window, then moves the cut back to the last configured punctuation mark after&amp;nbsp;&lt;code&gt;minChunkSizeChars&lt;/code&gt;. Finally, it trims the chunk and drops anything shorter than&amp;nbsp;&lt;code&gt;minChunkLengthToEmbed&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;Tokenization depends on the model. In this demo the embedding endpoint speaks an OpenAI-compatible API, but the model still runs&amp;nbsp;&lt;code&gt;text-embedding-nomic-embed-text-v1.5&lt;/code&gt;. That API shape does not make the tokenizer OpenAI-compatible. Nomic examples use a BERT tokenizer. Spring AI’s&amp;nbsp;&lt;code&gt;TokenTextSplitter&lt;/code&gt;&amp;nbsp;uses&amp;nbsp;&lt;code&gt;com.knuddels:jtokkit&lt;/code&gt;, a Java tokenizer for OpenAI-style encodings, and defaults to&amp;nbsp;&lt;code&gt;CL100K_BASE&lt;/code&gt;. Spring AI can switch among supported OpenAI-style encodings, but none matches a true BERT tokenizer.&lt;/p&gt;

&lt;p&gt;When the target model uses another encoding supported by&amp;nbsp;&lt;code&gt;jtokkit&lt;/code&gt;, set the encoding type on the&amp;nbsp;&lt;code&gt;TokenTextSplitter&lt;/code&gt;&amp;nbsp;builder.&lt;/p&gt;

&lt;p&gt;For Nomic, this does not give exact counts. A different&amp;nbsp;&lt;code&gt;EncodingType&lt;/code&gt;&amp;nbsp;will not close the gap because Nomic uses a different tokenizer family. If exact token accounting matters, swap in a custom&amp;nbsp;&lt;code&gt;DocumentTransformer&lt;/code&gt;. Back it with a Nomic/BERT-compatible tokenizer. Until then,&amp;nbsp;&lt;code&gt;TokenTextSplitter&lt;/code&gt;&amp;nbsp;still works as a safe local splitter.&lt;/p&gt;

&lt;p&gt;The local token count gives an estimate. I treat&amp;nbsp;&lt;code&gt;chunkSize&lt;/code&gt;&amp;nbsp;as a safety budget, not the model’s real limit. The exact endpoint limit depends on the local embedding server configuration. Chunks around 1000 tokens leave room for batch overhead. Exact counts need a Nomic/BERT-aware splitter or token counter.&lt;/p&gt;

&lt;h3&gt;
  
  
  Splitting text by tokens configuration
&lt;/h3&gt;

&lt;p&gt;For source code, I do not want chunks close to the endpoint limit: the batching strategy reserves space, Nomic token counts remain approximate here, and code has dense punctuation. A chunk size around 1000 tokens leaves room for the embedding request while keeping methods and classes searchable.&lt;/p&gt;

&lt;p&gt;Because the chunk limit belongs to the embedding model, configure the splitter as a shared bean rather than per-method setup. Spring AI will not apply this bean for you inside&amp;nbsp;&lt;code&gt;VectorStore.add(...)&lt;/code&gt;. The app still has to call the splitter in its indexing pipeline. One shared bean gives the project one chunking policy.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight java"&gt;&lt;code&gt;&lt;span class="nd"&gt;@Configuration&lt;/span&gt;
&lt;span class="kd"&gt;public&lt;/span&gt; &lt;span class="kd"&gt;class&lt;/span&gt; &lt;span class="nc"&gt;SourcesIndexingConfiguration&lt;/span&gt; &lt;span class="o"&gt;{&lt;/span&gt;

    &lt;span class="nd"&gt;@Bean&lt;/span&gt;
    &lt;span class="kd"&gt;public&lt;/span&gt; &lt;span class="nc"&gt;TokenTextSplitter&lt;/span&gt; &lt;span class="nf"&gt;tokenTextSplitter&lt;/span&gt;&lt;span class="o"&gt;()&lt;/span&gt; &lt;span class="o"&gt;{&lt;/span&gt;
        &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="nc"&gt;TokenTextSplitter&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;builder&lt;/span&gt;&lt;span class="o"&gt;()&lt;/span&gt;
                &lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;withEncodingType&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="nc"&gt;EncodingType&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;CL100K_BASE&lt;/span&gt;&lt;span class="o"&gt;)&lt;/span&gt;
                &lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;withChunkSize&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;1000&lt;/span&gt;&lt;span class="o"&gt;)&lt;/span&gt;
                &lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;withMinChunkSizeChars&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;400&lt;/span&gt;&lt;span class="o"&gt;)&lt;/span&gt;
                &lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;withMinChunkLengthToEmbed&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;10&lt;/span&gt;&lt;span class="o"&gt;)&lt;/span&gt;
                &lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;withMaxNumChunks&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;10000&lt;/span&gt;&lt;span class="o"&gt;)&lt;/span&gt;
                &lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;withKeepSeparator&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="kc"&gt;true&lt;/span&gt;&lt;span class="o"&gt;)&lt;/span&gt;
                &lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;withPunctuationMarks&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="nc"&gt;List&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;of&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="sc"&gt;'\n'&lt;/span&gt;&lt;span class="o"&gt;,&lt;/span&gt; &lt;span class="sc"&gt;';'&lt;/span&gt;&lt;span class="o"&gt;,&lt;/span&gt; &lt;span class="sc"&gt;'}'&lt;/span&gt;&lt;span class="o"&gt;))&lt;/span&gt;
                &lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;build&lt;/span&gt;&lt;span class="o"&gt;();&lt;/span&gt;
    &lt;span class="o"&gt;}&lt;/span&gt;
&lt;span class="o"&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;This still does not parse Java. It can split inside a method, a class, or a multiline expression. The project still gets a token safety layer: it keeps line breaks, prefers line or statement boundaries, and keeps ordinary source files well under the local embedding limit.&lt;/p&gt;

&lt;p&gt;&lt;code&gt;maxNumChunks&lt;/code&gt;&amp;nbsp;does not provide safe truncation. If you set it too low for a generated file, the final chunk can still contain the rest of the file and still trip the batching error. To reject generated files, do it at the file boundary by size, extension, or path.&lt;/p&gt;

&lt;p&gt;Chunking changes document identity. Before chunking, the deterministic id belongs to the source file. From here I call it the parent id. After chunking, the vector store stores chunk rows, and each one must still point back to the same source file.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight java"&gt;&lt;code&gt;&lt;span class="nc"&gt;String&lt;/span&gt; &lt;span class="n"&gt;parentDocumentId&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;documentId&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="n"&gt;library&lt;/span&gt;&lt;span class="o"&gt;,&lt;/span&gt; &lt;span class="n"&gt;relative&lt;/span&gt;&lt;span class="o"&gt;);&lt;/span&gt;

&lt;span class="nc"&gt;Document&lt;/span&gt; &lt;span class="n"&gt;sourceDocument&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="k"&gt;new&lt;/span&gt; &lt;span class="nc"&gt;Document&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="n"&gt;parentDocumentId&lt;/span&gt;&lt;span class="o"&gt;,&lt;/span&gt; &lt;span class="n"&gt;text&lt;/span&gt;&lt;span class="o"&gt;,&lt;/span&gt; &lt;span class="nc"&gt;Map&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;of&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;
        &lt;span class="no"&gt;LIBRARY_FIELD&lt;/span&gt;&lt;span class="o"&gt;,&lt;/span&gt; &lt;span class="n"&gt;library&lt;/span&gt;&lt;span class="o"&gt;,&lt;/span&gt;
        &lt;span class="no"&gt;PATH_FIELD&lt;/span&gt;&lt;span class="o"&gt;,&lt;/span&gt; &lt;span class="n"&gt;relative&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;toString&lt;/span&gt;&lt;span class="o"&gt;(),&lt;/span&gt;
        &lt;span class="no"&gt;CHECK_SUM_FIELD&lt;/span&gt;&lt;span class="o"&gt;,&lt;/span&gt; &lt;span class="n"&gt;checksum&lt;/span&gt;
&lt;span class="o"&gt;));&lt;/span&gt;

&lt;span class="nc"&gt;List&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="nc"&gt;Document&lt;/span&gt;&lt;span class="o"&gt;&amp;gt;&lt;/span&gt; &lt;span class="n"&gt;chunks&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;tokenTextSplitter&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;split&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="n"&gt;sourceDocument&lt;/span&gt;&lt;span class="o"&gt;);&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;This code still lacks full dedupe behavior. Spring AI’s&amp;nbsp;&lt;code&gt;TextSplitter&lt;/code&gt;&amp;nbsp;uses the id of&amp;nbsp;&lt;code&gt;sourceDocument&lt;/code&gt;&amp;nbsp;as the parent id, copies the original metadata, and adds&amp;nbsp;&lt;code&gt;parent_document_id&lt;/code&gt;,&amp;nbsp;&lt;code&gt;chunk_index&lt;/code&gt;, and&amp;nbsp;&lt;code&gt;total_chunks&lt;/code&gt;&amp;nbsp;to every chunk. We do not have to put&amp;nbsp;&lt;code&gt;parent_document_id&lt;/code&gt;&amp;nbsp;into the source document metadata ourselves.&lt;/p&gt;

&lt;p&gt;&lt;code&gt;TokenTextSplitter&lt;/code&gt;&amp;nbsp;creates new&amp;nbsp;&lt;code&gt;Document&lt;/code&gt;&amp;nbsp;instances instead of keeping the parent id as the chunk id. Those documents get random ids by default. That works for a one-off index, but it breaks deterministic PgVector upsert: a changed file inserts a fresh set of chunks and leaves the old chunks behind. The parent id only lives in metadata; PgVector’s&amp;nbsp;&lt;code&gt;ON CONFLICT (id) DO UPDATE&lt;/code&gt;&amp;nbsp;sees only the row id.&lt;/p&gt;

&lt;p&gt;Once one source file becomes many vector-store rows, the deterministic id moves from “one id per file” to “one id per chunk”. The file id remains the parent id. Each stored row gets a deterministic chunk id:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight java"&gt;&lt;code&gt;&lt;span class="kd"&gt;private&lt;/span&gt; &lt;span class="nc"&gt;String&lt;/span&gt; &lt;span class="nf"&gt;chunkId&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="nc"&gt;String&lt;/span&gt; &lt;span class="n"&gt;parentDocumentId&lt;/span&gt;&lt;span class="o"&gt;,&lt;/span&gt; &lt;span class="kt"&gt;int&lt;/span&gt; &lt;span class="n"&gt;chunkIndex&lt;/span&gt;&lt;span class="o"&gt;)&lt;/span&gt; &lt;span class="o"&gt;{&lt;/span&gt;
    &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="n"&gt;parentDocumentId&lt;/span&gt; &lt;span class="o"&gt;+&lt;/span&gt; &lt;span class="s"&gt;"#chunk-"&lt;/span&gt; &lt;span class="o"&gt;+&lt;/span&gt; &lt;span class="n"&gt;chunkIndex&lt;/span&gt;&lt;span class="o"&gt;;&lt;/span&gt;
&lt;span class="o"&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;After splitting, assign ids to the chunks. Each chunk needs a distinct deterministic id; otherwise PgVector would collapse the file to one row and each later chunk would overwrite the previous one. In the code below,&amp;nbsp;&lt;code&gt;chunkId(parentDocumentId, index)&lt;/code&gt;&amp;nbsp;produces stable ids like&amp;nbsp;&lt;code&gt;library/Foo.java#chunk-0&lt;/code&gt;,&amp;nbsp;&lt;code&gt;library/Foo.java#chunk-1&lt;/code&gt;, and so on. Repeat indexing updates the matching chunk row.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight java"&gt;&lt;code&gt;&lt;span class="nc"&gt;List&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="nc"&gt;Document&lt;/span&gt;&lt;span class="o"&gt;&amp;gt;&lt;/span&gt; &lt;span class="n"&gt;chunkDocuments&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nc"&gt;IntStream&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;range&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;0&lt;/span&gt;&lt;span class="o"&gt;,&lt;/span&gt; &lt;span class="n"&gt;chunks&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;size&lt;/span&gt;&lt;span class="o"&gt;())&lt;/span&gt;
        &lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;mapToObj&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="n"&gt;index&lt;/span&gt; &lt;span class="o"&gt;-&amp;gt;&lt;/span&gt; &lt;span class="k"&gt;new&lt;/span&gt; &lt;span class="nc"&gt;Document&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;
                &lt;span class="n"&gt;chunkId&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="n"&gt;parentDocumentId&lt;/span&gt;&lt;span class="o"&gt;,&lt;/span&gt; &lt;span class="n"&gt;index&lt;/span&gt;&lt;span class="o"&gt;),&lt;/span&gt;
                &lt;span class="n"&gt;chunks&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;get&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="n"&gt;index&lt;/span&gt;&lt;span class="o"&gt;).&lt;/span&gt;&lt;span class="na"&gt;getText&lt;/span&gt;&lt;span class="o"&gt;(),&lt;/span&gt;
                &lt;span class="n"&gt;chunks&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;get&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="n"&gt;index&lt;/span&gt;&lt;span class="o"&gt;).&lt;/span&gt;&lt;span class="na"&gt;getMetadata&lt;/span&gt;&lt;span class="o"&gt;()&lt;/span&gt;
        &lt;span class="o"&gt;))&lt;/span&gt;
        &lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;toList&lt;/span&gt;&lt;span class="o"&gt;();&lt;/span&gt;

&lt;span class="n"&gt;vectorStore&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;add&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="n"&gt;chunkDocuments&lt;/span&gt;&lt;span class="o"&gt;);&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Rebuild each chunk with&amp;nbsp;&lt;code&gt;new Document(id, text, metadata)&lt;/code&gt;&amp;nbsp;to preserve the metadata&amp;nbsp;&lt;code&gt;TextSplitter&lt;/code&gt;&amp;nbsp;added, including&amp;nbsp;&lt;code&gt;parent_document_id&lt;/code&gt;. That metadata supports stale-chunk cleanup later. The other option,&amp;nbsp;&lt;code&gt;chunks.get(index).mutate().id(...).build()&lt;/code&gt;, carries the metadata for you. But the explicit constructor keeps the storage identity rule visible in one place.&lt;/p&gt;

&lt;p&gt;I prefer to assign the chunk id in the indexing service. It keeps the storage identity rule next to the checksum and upsert logic. The splitter does not hide it.&lt;/p&gt;

&lt;p&gt;The checksum story changes too, but only a little. The source file still owns the checksum; chunks inherit that checksum in metadata. A small edit near the top of a file can shift all later chunk boundaries. Chunk-level hashes look less stable than they seem. For this indexer, the file acts as the unit of freshness.&lt;/p&gt;

&lt;p&gt;The unchanged-file check can still happen before embedding. Do not check the old file row id. Check the first deterministic chunk id plus the file checksum:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight java"&gt;&lt;code&gt;&lt;span class="nc"&gt;String&lt;/span&gt; &lt;span class="n"&gt;firstChunkId&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;chunkId&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="n"&gt;parentDocumentId&lt;/span&gt;&lt;span class="o"&gt;,&lt;/span&gt; &lt;span class="mi"&gt;0&lt;/span&gt;&lt;span class="o"&gt;);&lt;/span&gt;

&lt;span class="k"&gt;if&lt;/span&gt; &lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="n"&gt;queryService&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;isDocumentStoredByIdAndCheckSum&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="n"&gt;firstChunkId&lt;/span&gt;&lt;span class="o"&gt;,&lt;/span&gt; &lt;span class="n"&gt;checksum&lt;/span&gt;&lt;span class="o"&gt;))&lt;/span&gt; &lt;span class="o"&gt;{&lt;/span&gt;
    &lt;span class="n"&gt;log&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;debug&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="s"&gt;"Source document already stored: {}"&lt;/span&gt;&lt;span class="o"&gt;,&lt;/span&gt; &lt;span class="n"&gt;relative&lt;/span&gt;&lt;span class="o"&gt;);&lt;/span&gt;
    &lt;span class="k"&gt;return&lt;/span&gt;&lt;span class="o"&gt;;&lt;/span&gt;
&lt;span class="o"&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Checking chunk&amp;nbsp;&lt;code&gt;0&lt;/code&gt;&amp;nbsp;works for the demo, but it assumes indexing either stored every chunk or failed before storing the first chunk. If you need to tolerate partial indexing, store a manifest row per source file, or split first and compare the stored chunk count with&amp;nbsp;&lt;code&gt;total_chunks&lt;/code&gt;. That turns the check into a stronger invariant: the index holds the whole source file at this checksum.&lt;/p&gt;

&lt;p&gt;If the checksum changed, split the file, assign deterministic chunk ids, and call&amp;nbsp;&lt;code&gt;vectorStore.add(...)&lt;/code&gt;. PgVector will upsert chunks whose ids still exist.&lt;/p&gt;

&lt;p&gt;One cleanup case remains: a file used to produce ten chunks and now produces six. Upsert updates chunks&amp;nbsp;&lt;code&gt;0..5&lt;/code&gt;, but chunks&amp;nbsp;&lt;code&gt;6..9&lt;/code&gt;&amp;nbsp;go stale. Delete old chunks for that parent before or after reindexing the changed file. Because the splitter already adds&amp;nbsp;&lt;code&gt;parent_document_id&lt;/code&gt;, the cleanup can target the source file with one more&amp;nbsp;&lt;code&gt;JdbcTemplate&lt;/code&gt;&amp;nbsp;operation:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight java"&gt;&lt;code&gt;&lt;span class="kd"&gt;public&lt;/span&gt; &lt;span class="kt"&gt;void&lt;/span&gt; &lt;span class="nf"&gt;deleteStaleChunks&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="nc"&gt;String&lt;/span&gt; &lt;span class="n"&gt;parentDocumentId&lt;/span&gt;&lt;span class="o"&gt;,&lt;/span&gt; &lt;span class="nc"&gt;Long&lt;/span&gt; &lt;span class="n"&gt;checksum&lt;/span&gt;&lt;span class="o"&gt;)&lt;/span&gt; &lt;span class="o"&gt;{&lt;/span&gt;
    &lt;span class="n"&gt;jdbcTemplate&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;update&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="sh"&gt;"""
            delete from public.vector_store
            where metadata -&amp;gt;&amp;gt; 'parent_document_id' = ?
              and metadata -&amp;gt;&amp;gt; 'checksum' is distinct from ?
            """&lt;/span&gt;&lt;span class="o"&gt;,&lt;/span&gt; &lt;span class="n"&gt;parentDocumentId&lt;/span&gt;&lt;span class="o"&gt;,&lt;/span&gt; &lt;span class="n"&gt;checksum&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;toString&lt;/span&gt;&lt;span class="o"&gt;());&lt;/span&gt;
&lt;span class="o"&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;This storage model makes a reliable Spring AI RAG indexer: deterministic identity, checksum metadata, a cheap JDBC pre-check, and PgVector upsert. Chunking only makes the identity model more exact. The file acts as the parent document. The vector-store rows hold chunk documents.&lt;/p&gt;

&lt;p&gt;For better source-code retrieval later, replace the local&amp;nbsp;&lt;code&gt;TokenTextSplitter&lt;/code&gt;&amp;nbsp;setup with a code-aware splitter that understands classes, methods, and declarations. The same storage rules still hold: deterministic chunk ids, file-level checksum metadata, and stale-chunk cleanup when a file changes. With those rules in place, your Spring AI RAG pipeline stays idempotent as dependency sources grow and change.&lt;/p&gt;

&lt;h2&gt;
  
  
  From index to answers: a grounded chat client
&lt;/h2&gt;

&lt;p&gt;The index only covers half the system. Now we read from it. In the&amp;nbsp;&lt;a href="https://protsenko.dev/spring-ai-for-beginners-build-your-first-ai-app-in-java/" rel="noopener noreferrer"&gt;Spring AI beginner guide&lt;/a&gt;, a small&amp;nbsp;&lt;code&gt;@Service&lt;/code&gt;&amp;nbsp;wrapped a&amp;nbsp;&lt;code&gt;ChatClient&lt;/code&gt;; then I added a memory advisor and a&amp;nbsp;&lt;code&gt;QuestionAnswerAdvisor&lt;/code&gt;. Here we point that same shape at the&amp;nbsp;&lt;code&gt;VectorStore&lt;/code&gt;&amp;nbsp;the indexer fills, so the code assistant answers from indexed sources instead of model training data.&lt;/p&gt;

&lt;p&gt;To make the answer machine-readable, we ask for structured output instead of free text. The reply carries the prose answer, the snippets it leaned on, and the files those snippets came from.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight java"&gt;&lt;code&gt;&lt;span class="kd"&gt;public&lt;/span&gt; &lt;span class="kd"&gt;record&lt;/span&gt; &lt;span class="nf"&gt;CodeAssistantReply&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;
        &lt;span class="nc"&gt;String&lt;/span&gt; &lt;span class="n"&gt;answer&lt;/span&gt;&lt;span class="o"&gt;,&lt;/span&gt;
        &lt;span class="nc"&gt;List&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="nc"&gt;String&lt;/span&gt;&lt;span class="o"&gt;&amp;gt;&lt;/span&gt; &lt;span class="n"&gt;evidences&lt;/span&gt;&lt;span class="o"&gt;,&lt;/span&gt;
        &lt;span class="nc"&gt;List&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="nc"&gt;String&lt;/span&gt;&lt;span class="o"&gt;&amp;gt;&lt;/span&gt; &lt;span class="n"&gt;absoluteSourceFilePaths&lt;/span&gt;
&lt;span class="o"&gt;)&lt;/span&gt; &lt;span class="o"&gt;{}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The first service version kept things minimal: wire the two advisors, set a system prompt, and map the model’s JSON onto the record with&amp;nbsp;&lt;code&gt;.entity(...)&lt;/code&gt;. That version helps explain the failure, but the checked-in project now uses the grounded version shown below.&lt;/p&gt;

&lt;p&gt;A thin controller gives the conversation an id when the caller omits one, so memory keeps separate chats apart:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight java"&gt;&lt;code&gt;&lt;span class="nd"&gt;@RestController&lt;/span&gt;
&lt;span class="nd"&gt;@RequestMapping&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="s"&gt;"/api/chat"&lt;/span&gt;&lt;span class="o"&gt;)&lt;/span&gt;
&lt;span class="nd"&gt;@RequiredArgsConstructor&lt;/span&gt;
&lt;span class="kd"&gt;public&lt;/span&gt; &lt;span class="kd"&gt;class&lt;/span&gt; &lt;span class="nc"&gt;ChatController&lt;/span&gt; &lt;span class="o"&gt;{&lt;/span&gt;
    &lt;span class="kd"&gt;private&lt;/span&gt; &lt;span class="kd"&gt;final&lt;/span&gt; &lt;span class="nc"&gt;CodeAssistantService&lt;/span&gt; &lt;span class="n"&gt;codeAssistantService&lt;/span&gt;&lt;span class="o"&gt;;&lt;/span&gt;

    &lt;span class="nd"&gt;@PostMapping&lt;/span&gt;
    &lt;span class="kd"&gt;public&lt;/span&gt; &lt;span class="nc"&gt;GenerationResponse&lt;/span&gt; &lt;span class="nf"&gt;generation&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="nd"&gt;@RequestBody&lt;/span&gt; &lt;span class="nc"&gt;GenerationRequest&lt;/span&gt; &lt;span class="n"&gt;request&lt;/span&gt;&lt;span class="o"&gt;)&lt;/span&gt; &lt;span class="o"&gt;{&lt;/span&gt;
        &lt;span class="kt"&gt;var&lt;/span&gt; &lt;span class="n"&gt;conversationId&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;request&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;conversationId&lt;/span&gt;&lt;span class="o"&gt;();&lt;/span&gt;
        &lt;span class="k"&gt;if&lt;/span&gt; &lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="n"&gt;conversationId&lt;/span&gt; &lt;span class="o"&gt;==&lt;/span&gt; &lt;span class="kc"&gt;null&lt;/span&gt;&lt;span class="o"&gt;)&lt;/span&gt; &lt;span class="o"&gt;{&lt;/span&gt;
            &lt;span class="n"&gt;conversationId&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="no"&gt;UUID&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;randomUUID&lt;/span&gt;&lt;span class="o"&gt;().&lt;/span&gt;&lt;span class="na"&gt;toString&lt;/span&gt;&lt;span class="o"&gt;();&lt;/span&gt;
        &lt;span class="o"&gt;}&lt;/span&gt;
        &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="k"&gt;new&lt;/span&gt; &lt;span class="nf"&gt;GenerationResponse&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;
                &lt;span class="n"&gt;codeAssistantService&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;ask&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="n"&gt;conversationId&lt;/span&gt;&lt;span class="o"&gt;,&lt;/span&gt; &lt;span class="n"&gt;request&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;userMessage&lt;/span&gt;&lt;span class="o"&gt;())&lt;/span&gt;
        &lt;span class="o"&gt;);&lt;/span&gt;
    &lt;span class="o"&gt;}&lt;/span&gt;
&lt;span class="o"&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Use the checked-in&amp;nbsp;&lt;code&gt;requests/chat-controller.http&lt;/code&gt;&amp;nbsp;request unchanged. It asks the assistant about an MCP client:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight http"&gt;&lt;code&gt;&lt;span class="err"&gt;POST localhost:8080/api/chat
Content-Type: application/json

{
  "userMessage": "What's mcp client and how to use it?"
}
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The&amp;nbsp;&lt;code&gt;answer&lt;/code&gt;&amp;nbsp;looks useful, and the&amp;nbsp;&lt;code&gt;evidences&lt;/code&gt;&amp;nbsp;look plausible. Then you check&amp;nbsp;&lt;code&gt;absoluteSourceFilePaths&lt;/code&gt;: the files do not exist. The model returned paths it never saw. To understand why, look at what&amp;nbsp;&lt;code&gt;QuestionAnswerAdvisor&lt;/code&gt;&amp;nbsp;actually puts into the prompt.&lt;/p&gt;

&lt;h2&gt;
  
  
  How Spring AI QuestionAnswerAdvisor grounds a RAG prompt
&lt;/h2&gt;

&lt;p&gt;&lt;code&gt;QuestionAnswerAdvisor&lt;/code&gt;&amp;nbsp;packages the retrieval step of Spring AI RAG as an advisor. On every call it does three things before the model runs.&lt;/p&gt;

&lt;p&gt;First, it searches the vector store with the user’s question as the query:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight java"&gt;&lt;code&gt;&lt;span class="nc"&gt;List&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="nc"&gt;Document&lt;/span&gt;&lt;span class="o"&gt;&amp;gt;&lt;/span&gt; &lt;span class="n"&gt;documents&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="k"&gt;this&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;vectorStore&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;similaritySearch&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="n"&gt;searchRequestToUse&lt;/span&gt;&lt;span class="o"&gt;);&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Second, it turns those hits into a context string. This line matters for our bug:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight java"&gt;&lt;code&gt;&lt;span class="nc"&gt;String&lt;/span&gt; &lt;span class="n"&gt;documentContext&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;documents&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;stream&lt;/span&gt;&lt;span class="o"&gt;()&lt;/span&gt;
        &lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;map&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="nl"&gt;Document:&lt;/span&gt;&lt;span class="o"&gt;:&lt;/span&gt;&lt;span class="n"&gt;getText&lt;/span&gt;&lt;span class="o"&gt;)&lt;/span&gt;
        &lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;collect&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="nc"&gt;Collectors&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;joining&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="nc"&gt;System&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;lineSeparator&lt;/span&gt;&lt;span class="o"&gt;()));&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;It joins&amp;nbsp;&lt;code&gt;Document.getText()&lt;/code&gt;&amp;nbsp;and nothing else. The chunk metadata, including the&amp;nbsp;&lt;code&gt;library&lt;/code&gt;,&amp;nbsp;&lt;code&gt;path&lt;/code&gt;, and&amp;nbsp;&lt;code&gt;checksum&lt;/code&gt;&amp;nbsp;fields the indexer stored, never enters the string.&lt;/p&gt;

&lt;p&gt;Third, it renders a default template that wraps the question and that context together:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;{query}

Context information is below, surrounded by ---------------------

---------------------
{question_answer_context}
---------------------

Given the context and provided history information and not prior knowledge,
reply to the user comment. If the answer is not in the context, inform
the user that you can't answer the question.
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The model sees code text and an instruction to answer from it, but no file paths. The retrieved documents still exist in Java: the advisor stores them under&amp;nbsp;&lt;code&gt;QuestionAnswerAdvisor.RETRIEVED_DOCUMENTS&lt;/code&gt;&amp;nbsp;and copies them to&amp;nbsp;&lt;code&gt;ChatResponse&lt;/code&gt;metadata after the call. The path data becomes available after the call, but not in the prompt.&lt;/p&gt;

&lt;h2&gt;
  
  
  When the model invents file paths
&lt;/h2&gt;

&lt;p&gt;The bad output has three causes. The model never receives a path. The structured-output converter appends the JSON schema for&amp;nbsp;&lt;code&gt;CodeAssistantReply&lt;/code&gt;, so the model sees an&amp;nbsp;&lt;code&gt;absoluteSourceFilePaths&lt;/code&gt;&amp;nbsp;field. And the original prompt tells it to fill that field with real file locations. With no path data in context, the model writes plausible strings that point at nothing.&lt;/p&gt;

&lt;p&gt;First, make the failure visible instead of guessing at it. Three checks, cheapest first.&lt;/p&gt;

&lt;p&gt;Turn on advisor logging while debugging.&amp;nbsp;&lt;code&gt;SimpleLoggerAdvisor&lt;/code&gt;&amp;nbsp;can print the request the model receives, including the augmented user message, so you can confirm the prompt carries code but no paths.&lt;/p&gt;

&lt;p&gt;Inspect what retrieval returned. Response metadata contains the documents, so you can compare their real paths with the model’s claimed ones.&lt;/p&gt;

&lt;p&gt;When you add tests, pin the invariant: every cited path must resolve to a real file under the indexed root. If evidence must come from real quotes, add a second assertion that each evidence string appears in the joined retrieved text.&lt;/p&gt;

&lt;h2&gt;
  
  
  Add file citations to a Spring AI RAG response
&lt;/h2&gt;

&lt;p&gt;The fix follows from the mechanics: stop asking the model for paths, and read them from retrieval instead. Let the model write the answer and quote evidence. Let the service take paths from the documents the advisor already retrieved.&lt;/p&gt;

&lt;p&gt;To reach both the parsed entity and the raw response, swap&amp;nbsp;&lt;code&gt;.entity(...)&lt;/code&gt;&amp;nbsp;for&amp;nbsp;&lt;code&gt;.responseEntity(...)&lt;/code&gt;. That call returns both objects: the converted&amp;nbsp;&lt;code&gt;CodeAssistantReply&lt;/code&gt;&amp;nbsp;and the full&amp;nbsp;&lt;code&gt;ChatResponse&lt;/code&gt;, whose metadata carries&amp;nbsp;&lt;code&gt;RETRIEVED_DOCUMENTS&lt;/code&gt;.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight java"&gt;&lt;code&gt;&lt;span class="nd"&gt;@Service&lt;/span&gt;
&lt;span class="kd"&gt;public&lt;/span&gt; &lt;span class="kd"&gt;class&lt;/span&gt; &lt;span class="nc"&gt;CodeAssistantService&lt;/span&gt; &lt;span class="o"&gt;{&lt;/span&gt;

    &lt;span class="kd"&gt;private&lt;/span&gt; &lt;span class="kd"&gt;final&lt;/span&gt; &lt;span class="nc"&gt;ChatClient&lt;/span&gt; &lt;span class="n"&gt;chatClient&lt;/span&gt;&lt;span class="o"&gt;;&lt;/span&gt;

    &lt;span class="kd"&gt;private&lt;/span&gt; &lt;span class="kd"&gt;static&lt;/span&gt; &lt;span class="kd"&gt;final&lt;/span&gt; &lt;span class="nc"&gt;String&lt;/span&gt; &lt;span class="n"&gt;systemPrompt&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="sh"&gt;"""
            You are a code assistant that explains how libraries and frameworks work.

            Answer ONLY from the context block provided below the user's question. That
            context is real source code retrieved from the user's own dependency sources.

            Rules:
            - Ground every statement in the provided context. Do not rely on prior knowledge of the library, and do not guess.
            - In `evidences`, copy short verbatim snippets from the context that back your answer.
            - If the context does not contain the answer, say so plainly in `answer` and return empty lists.
            - Leave `absoluteSourceFilePaths` empty. The system fills it from retrieval metadata. Never invent file paths.
            """&lt;/span&gt;&lt;span class="o"&gt;;&lt;/span&gt;

    &lt;span class="nc"&gt;CodeAssistantService&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="nc"&gt;ChatClient&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;Builder&lt;/span&gt; &lt;span class="n"&gt;builder&lt;/span&gt;&lt;span class="o"&gt;,&lt;/span&gt; &lt;span class="nc"&gt;VectorStore&lt;/span&gt; &lt;span class="n"&gt;vectorStore&lt;/span&gt;&lt;span class="o"&gt;)&lt;/span&gt; &lt;span class="o"&gt;{&lt;/span&gt;
        &lt;span class="kt"&gt;var&lt;/span&gt; &lt;span class="n"&gt;chatMemory&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nc"&gt;MessageWindowChatMemory&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;builder&lt;/span&gt;&lt;span class="o"&gt;().&lt;/span&gt;&lt;span class="na"&gt;build&lt;/span&gt;&lt;span class="o"&gt;();&lt;/span&gt;
        &lt;span class="kt"&gt;var&lt;/span&gt; &lt;span class="n"&gt;memoryAdvisor&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nc"&gt;MessageChatMemoryAdvisor&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;builder&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="n"&gt;chatMemory&lt;/span&gt;&lt;span class="o"&gt;).&lt;/span&gt;&lt;span class="na"&gt;build&lt;/span&gt;&lt;span class="o"&gt;();&lt;/span&gt;
        &lt;span class="kt"&gt;var&lt;/span&gt; &lt;span class="n"&gt;questionAnswerAdvisor&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nc"&gt;QuestionAnswerAdvisor&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;builder&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="n"&gt;vectorStore&lt;/span&gt;&lt;span class="o"&gt;).&lt;/span&gt;&lt;span class="na"&gt;build&lt;/span&gt;&lt;span class="o"&gt;();&lt;/span&gt;

        &lt;span class="k"&gt;this&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;chatClient&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;builder&lt;/span&gt;
                &lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;defaultSystem&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="n"&gt;systemPrompt&lt;/span&gt;&lt;span class="o"&gt;)&lt;/span&gt;
                &lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;defaultAdvisors&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="n"&gt;memoryAdvisor&lt;/span&gt;&lt;span class="o"&gt;,&lt;/span&gt; &lt;span class="n"&gt;questionAnswerAdvisor&lt;/span&gt;&lt;span class="o"&gt;)&lt;/span&gt;
                &lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;build&lt;/span&gt;&lt;span class="o"&gt;();&lt;/span&gt;
    &lt;span class="o"&gt;}&lt;/span&gt;

    &lt;span class="kd"&gt;public&lt;/span&gt; &lt;span class="nc"&gt;CodeAssistantReply&lt;/span&gt; &lt;span class="nf"&gt;ask&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="nc"&gt;String&lt;/span&gt; &lt;span class="n"&gt;conversationId&lt;/span&gt;&lt;span class="o"&gt;,&lt;/span&gt; &lt;span class="nc"&gt;String&lt;/span&gt; &lt;span class="n"&gt;question&lt;/span&gt;&lt;span class="o"&gt;)&lt;/span&gt; &lt;span class="o"&gt;{&lt;/span&gt;
        &lt;span class="nc"&gt;ResponseEntity&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="nc"&gt;ChatResponse&lt;/span&gt;&lt;span class="o"&gt;,&lt;/span&gt; &lt;span class="nc"&gt;CodeAssistantReply&lt;/span&gt;&lt;span class="o"&gt;&amp;gt;&lt;/span&gt; &lt;span class="n"&gt;result&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;chatClient&lt;/span&gt;
                &lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;prompt&lt;/span&gt;&lt;span class="o"&gt;()&lt;/span&gt;
                &lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;user&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="n"&gt;question&lt;/span&gt;&lt;span class="o"&gt;)&lt;/span&gt;
                &lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;advisors&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="n"&gt;spec&lt;/span&gt; &lt;span class="o"&gt;-&amp;gt;&lt;/span&gt; &lt;span class="n"&gt;spec&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;param&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="nc"&gt;ChatMemory&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;CONVERSATION_ID&lt;/span&gt;&lt;span class="o"&gt;,&lt;/span&gt; &lt;span class="n"&gt;conversationId&lt;/span&gt;&lt;span class="o"&gt;))&lt;/span&gt;
                &lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;call&lt;/span&gt;&lt;span class="o"&gt;()&lt;/span&gt;
                &lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;responseEntity&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="nc"&gt;CodeAssistantReply&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;class&lt;/span&gt;&lt;span class="o"&gt;);&lt;/span&gt;

        &lt;span class="nc"&gt;CodeAssistantReply&lt;/span&gt; &lt;span class="n"&gt;reply&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;result&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;entity&lt;/span&gt;&lt;span class="o"&gt;();&lt;/span&gt;
        &lt;span class="k"&gt;if&lt;/span&gt; &lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="n"&gt;reply&lt;/span&gt; &lt;span class="o"&gt;==&lt;/span&gt; &lt;span class="kc"&gt;null&lt;/span&gt;&lt;span class="o"&gt;)&lt;/span&gt; &lt;span class="o"&gt;{&lt;/span&gt;
            &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="kc"&gt;null&lt;/span&gt;&lt;span class="o"&gt;;&lt;/span&gt;
        &lt;span class="o"&gt;}&lt;/span&gt;
        &lt;span class="nc"&gt;List&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="nc"&gt;String&lt;/span&gt;&lt;span class="o"&gt;&amp;gt;&lt;/span&gt; &lt;span class="n"&gt;realPaths&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;retrievedPaths&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="n"&gt;result&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;response&lt;/span&gt;&lt;span class="o"&gt;());&lt;/span&gt;

        &lt;span class="c1"&gt;// Real paths overwrite whatever the model produced.&lt;/span&gt;
        &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="k"&gt;new&lt;/span&gt; &lt;span class="nf"&gt;CodeAssistantReply&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="n"&gt;reply&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;answer&lt;/span&gt;&lt;span class="o"&gt;(),&lt;/span&gt; &lt;span class="n"&gt;reply&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;evidences&lt;/span&gt;&lt;span class="o"&gt;(),&lt;/span&gt; &lt;span class="n"&gt;realPaths&lt;/span&gt;&lt;span class="o"&gt;);&lt;/span&gt;
    &lt;span class="o"&gt;}&lt;/span&gt;

    &lt;span class="kd"&gt;private&lt;/span&gt; &lt;span class="nc"&gt;List&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="nc"&gt;String&lt;/span&gt;&lt;span class="o"&gt;&amp;gt;&lt;/span&gt; &lt;span class="nf"&gt;retrievedPaths&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="nc"&gt;ChatResponse&lt;/span&gt; &lt;span class="n"&gt;chatResponse&lt;/span&gt;&lt;span class="o"&gt;)&lt;/span&gt; &lt;span class="o"&gt;{&lt;/span&gt;
        &lt;span class="k"&gt;if&lt;/span&gt; &lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="n"&gt;chatResponse&lt;/span&gt; &lt;span class="o"&gt;==&lt;/span&gt; &lt;span class="kc"&gt;null&lt;/span&gt;&lt;span class="o"&gt;)&lt;/span&gt; &lt;span class="o"&gt;{&lt;/span&gt;
            &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="nc"&gt;List&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;of&lt;/span&gt;&lt;span class="o"&gt;();&lt;/span&gt;
        &lt;span class="o"&gt;}&lt;/span&gt;
        &lt;span class="nc"&gt;List&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="nc"&gt;Document&lt;/span&gt;&lt;span class="o"&gt;&amp;gt;&lt;/span&gt; &lt;span class="n"&gt;documents&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt;
                &lt;span class="n"&gt;chatResponse&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;getMetadata&lt;/span&gt;&lt;span class="o"&gt;().&lt;/span&gt;&lt;span class="na"&gt;get&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="nc"&gt;QuestionAnswerAdvisor&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;RETRIEVED_DOCUMENTS&lt;/span&gt;&lt;span class="o"&gt;);&lt;/span&gt;
        &lt;span class="k"&gt;if&lt;/span&gt; &lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="n"&gt;documents&lt;/span&gt; &lt;span class="o"&gt;==&lt;/span&gt; &lt;span class="kc"&gt;null&lt;/span&gt;&lt;span class="o"&gt;)&lt;/span&gt; &lt;span class="o"&gt;{&lt;/span&gt;
            &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="nc"&gt;List&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;of&lt;/span&gt;&lt;span class="o"&gt;();&lt;/span&gt;
        &lt;span class="o"&gt;}&lt;/span&gt;
        &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="n"&gt;documents&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;stream&lt;/span&gt;&lt;span class="o"&gt;()&lt;/span&gt;
                &lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;map&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="n"&gt;d&lt;/span&gt; &lt;span class="o"&gt;-&amp;gt;&lt;/span&gt; &lt;span class="n"&gt;d&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;getMetadata&lt;/span&gt;&lt;span class="o"&gt;().&lt;/span&gt;&lt;span class="na"&gt;get&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="nc"&gt;MetadataFields&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;PATH_FIELD&lt;/span&gt;&lt;span class="o"&gt;))&lt;/span&gt;
                &lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;filter&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="nl"&gt;Objects:&lt;/span&gt;&lt;span class="o"&gt;:&lt;/span&gt;&lt;span class="n"&gt;nonNull&lt;/span&gt;&lt;span class="o"&gt;)&lt;/span&gt;
                &lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;map&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="nl"&gt;Object:&lt;/span&gt;&lt;span class="o"&gt;:&lt;/span&gt;&lt;span class="n"&gt;toString&lt;/span&gt;&lt;span class="o"&gt;)&lt;/span&gt;
                &lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;distinct&lt;/span&gt;&lt;span class="o"&gt;()&lt;/span&gt;
                &lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;toList&lt;/span&gt;&lt;span class="o"&gt;();&lt;/span&gt;
    &lt;span class="o"&gt;}&lt;/span&gt;
&lt;span class="o"&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Two changes fix it. The system prompt tells the model to leave&amp;nbsp;&lt;code&gt;absoluteSourceFilePaths&lt;/code&gt;&amp;nbsp;empty, which removes the temptation to invent. Then&amp;nbsp;&lt;code&gt;retrievedPaths(...)&lt;/code&gt;&amp;nbsp;reads&amp;nbsp;&lt;code&gt;RETRIEVED_DOCUMENTS&lt;/code&gt;&amp;nbsp;from response metadata, pulls the&amp;nbsp;&lt;code&gt;path&lt;/code&gt;&amp;nbsp;field from each document, and overwrites the field the model returned. The index now supplies the paths as facts, not guesses.&lt;/p&gt;

&lt;p&gt;One caveat about the field name. The indexer stored&amp;nbsp;&lt;code&gt;PATH_FIELD&lt;/code&gt;&amp;nbsp;as&amp;nbsp;&lt;code&gt;relative.toString()&lt;/code&gt;, so metadata holds a path relative to the indexed root, not an absolute one. If you want a full path, either store&amp;nbsp;&lt;code&gt;file.toAbsolutePath().toString()&lt;/code&gt;&amp;nbsp;at index time, or resolve the relative path against the known sources root when you build the reply.&lt;/p&gt;

&lt;p&gt;Use this pattern for grounded answers in Spring AI RAG: let the model reason over retrieved text, but take citable facts such as paths, ids, and versions from the retrieved documents themselves. The advisor exposes those documents in response metadata. The mistake comes from asking the model to repeat data the prompt never showed.&lt;/p&gt;

&lt;h3&gt;
  
  
  The client reply differs from the model’s message
&lt;/h3&gt;

&lt;p&gt;Precision helps because three versions of the answer exist.&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;The model produces an assistant message: JSON text with&amp;nbsp;&lt;code&gt;answer&lt;/code&gt;,&amp;nbsp;&lt;code&gt;evidences&lt;/code&gt;, and whatever it guessed for&amp;nbsp;&lt;code&gt;absoluteSourceFilePaths&lt;/code&gt;.&lt;/li&gt;
&lt;li&gt;Inside the call, the advisors run and the structured-output converter maps that text onto a&amp;nbsp;&lt;code&gt;CodeAssistantReply&lt;/code&gt;.&lt;/li&gt;
&lt;li&gt;In&amp;nbsp;&lt;code&gt;ask(...)&lt;/code&gt;, your code replaces the paths and builds a new&amp;nbsp;&lt;code&gt;CodeAssistantReply&lt;/code&gt;. The controller returns that new record to the client.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;The model never sees step 3. It only produced the message in step 1. Your code creates the corrected reply after the model finishes and outside its view.&lt;/p&gt;

&lt;p&gt;That split has one consequence for memory.&amp;nbsp;&lt;code&gt;MessageChatMemoryAdvisor&lt;/code&gt;&amp;nbsp;saves history in its&amp;nbsp;&lt;code&gt;after&lt;/code&gt;&amp;nbsp;step, and it saves the model’s own output, not your record:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight java"&gt;&lt;code&gt;&lt;span class="n"&gt;assistantMessages&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;chatClientResponse&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;chatResponse&lt;/span&gt;&lt;span class="o"&gt;()&lt;/span&gt;
    &lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;getResults&lt;/span&gt;&lt;span class="o"&gt;()&lt;/span&gt;
    &lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;stream&lt;/span&gt;&lt;span class="o"&gt;()&lt;/span&gt;
    &lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;map&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="n"&gt;g&lt;/span&gt; &lt;span class="o"&gt;-&amp;gt;&lt;/span&gt; &lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="nc"&gt;Message&lt;/span&gt;&lt;span class="o"&gt;)&lt;/span&gt; &lt;span class="n"&gt;g&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;getOutput&lt;/span&gt;&lt;span class="o"&gt;())&lt;/span&gt;
    &lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;toList&lt;/span&gt;&lt;span class="o"&gt;();&lt;/span&gt;
&lt;span class="k"&gt;this&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;chatMemory&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;add&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="n"&gt;conversationId&lt;/span&gt;&lt;span class="o"&gt;,&lt;/span&gt; &lt;span class="n"&gt;assistantMessages&lt;/span&gt;&lt;span class="o"&gt;);&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Chat memory keeps the message from step 1. The user saw one version, but the next turn remembers another.&lt;/p&gt;

&lt;p&gt;The refined system prompt makes memory less risky because it tells the model to leave&amp;nbsp;&lt;code&gt;absoluteSourceFilePaths&lt;/code&gt;&amp;nbsp;empty. The broader rule still matters. Paths, redactions, reranked evidence, and other post-call changes exist only in the reply you return. If later turns must reason over that corrected reply, store the corrected assistant message under the same conversation id.&lt;/p&gt;

&lt;p&gt;Keep the two roles apart. The model writes the answer from context. Your service owns the final reply and what gets stored for later turns.&lt;/p&gt;

&lt;h2&gt;
  
  
  Where to go next with Spring AI RAG
&lt;/h2&gt;

&lt;p&gt;You now have a repeatable Spring AI RAG pipeline: export source jars, skip unchanged files, split the files that changed, store deterministic chunks in PgVector, and take citations from retrieval metadata instead of model output.&lt;/p&gt;

&lt;p&gt;For the engineering workflow around it, read &lt;a href="https://protsenko.dev/ai-driven-development-workflow-guard-rails/" rel="noopener noreferrer"&gt;AI Coding Workflow: TDD, Reviews, and Guardrails&lt;/a&gt;, see where automated reviews still fall short in &lt;a href="https://protsenko.dev/ai-code-review-7-limitations-i-found-in-production/" rel="noopener noreferrer"&gt;AI Code Review: 7 Limitations I Found in Production&lt;/a&gt;, or browse all &lt;a href="https://protsenko.dev/category/artificial-intelligence/" rel="noopener noreferrer"&gt;artificial intelligence articles&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;New to Spring AI? Start with &lt;a href="https://protsenko.dev/spring-ai-for-beginners-build-your-first-ai-app-in-java/" rel="noopener noreferrer"&gt;Spring AI for beginners: build your first AI app in Java&lt;/a&gt;.&lt;/strong&gt;&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;&lt;strong&gt;Found this useful?&lt;/strong&gt; Follow me on social media to stay updated.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://t.me/protsenko_dev" rel="noopener noreferrer"&gt;Telegram&lt;/a&gt; · &lt;a href="https://www.linkedin.com/in/protsenkodev/" rel="noopener noreferrer"&gt;LinkedIn&lt;/a&gt;&lt;/p&gt;
&lt;/blockquote&gt;

</description>
      <category>java</category>
      <category>spring</category>
      <category>ai</category>
      <category>rag</category>
    </item>
    <item>
      <title>Spring AI for beginners: build your first AI app in Java</title>
      <dc:creator>Dmitry Protsenko</dc:creator>
      <pubDate>Mon, 09 Nov 2026 15:00:00 +0000</pubDate>
      <link>https://dev.to/protsenko/spring-ai-for-beginners-build-your-first-ai-app-in-java-4amn</link>
      <guid>https://dev.to/protsenko/spring-ai-for-beginners-build-your-first-ai-app-in-java-4amn</guid>
      <description>&lt;p&gt;Spring AI is an application framework for AI engineering on the JVM. It lets you talk to large language models with the same fluent, dependency-injected style you already use for the web and the database.&lt;/p&gt;

&lt;p&gt;This is a beginner’s tour. By the end you will know what Spring AI is and how to make your first model call, then connect RAG and memory from a plain Spring Boot app.&lt;/p&gt;

&lt;h2&gt;
  
  
  Table of contents
&lt;/h2&gt;

&lt;ul&gt;
&lt;li&gt;What Spring AI is&lt;/li&gt;
&lt;li&gt;Your first call: the ChatClient&lt;/li&gt;
&lt;li&gt;Setting up Spring AI&lt;/li&gt;
&lt;li&gt;
Useful building blocks in Spring AI

&lt;ul&gt;
&lt;li&gt;System prompts&lt;/li&gt;
&lt;li&gt;Advisors&lt;/li&gt;
&lt;li&gt;Vector stores and embeddings&lt;/li&gt;
&lt;li&gt;Using RAG with Spring AI&lt;/li&gt;
&lt;li&gt;Tool calling&lt;/li&gt;
&lt;li&gt;Structured output&lt;/li&gt;
&lt;li&gt;Model Context Protocol (MCP)&lt;/li&gt;
&lt;li&gt;The supporting cast&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;li&gt;Where to go next with Spring AI&lt;/li&gt;
&lt;/ul&gt;

&lt;h2&gt;
  
  
  What Spring AI is
&lt;/h2&gt;

&lt;p&gt;Spring AI is, in the project’s own words, “an application framework for AI engineering. Its goal is to apply to the AI domain Spring ecosystem design principles such as portability and modular design.”&lt;/p&gt;

&lt;p&gt;That tells you what to expect. Spring AI is not a new model. It does not compete with OpenAI or Anthropic. It is the integration layer between your Java application and whatever model you pick. The team frames the core problem it solves as “connecting your enterprise data and APIs with AI models.”&lt;/p&gt;

&lt;p&gt;If you have heard of LangChain in the Python world, you already have a mental model. It brings the same idea (abstractions over models, prompts, retrieval, and memory) to the JVM, with Spring Boot auto-configuration doing the wiring you would otherwise write by hand.&lt;/p&gt;

&lt;h2&gt;
  
  
  Your first call: the ChatClient
&lt;/h2&gt;

&lt;p&gt;The center of the beginner experience is the&amp;nbsp;&lt;code&gt;ChatClient&lt;/code&gt;. The docs describe it as a “fluent API for communicating with AI chat models, idiomatically similar to the&amp;nbsp;&lt;code&gt;WebClient&lt;/code&gt;&amp;nbsp;and&amp;nbsp;&lt;code&gt;RestClient&lt;/code&gt;&amp;nbsp;APIs.” If you have used either, this will feel familiar.&lt;/p&gt;

&lt;p&gt;Spring Boot auto-configures a&amp;nbsp;&lt;code&gt;ChatClient.Builder&lt;/code&gt;&amp;nbsp;for you. Inject it and build the client. In a real endpoint, keep the HTTP contract explicit with request and response DTOs:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight java"&gt;&lt;code&gt;&lt;span class="nd"&gt;@RestController&lt;/span&gt;
&lt;span class="nd"&gt;@RequestMapping&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="s"&gt;"/api/chat"&lt;/span&gt;&lt;span class="o"&gt;)&lt;/span&gt;
&lt;span class="kd"&gt;public&lt;/span&gt; &lt;span class="kd"&gt;class&lt;/span&gt; &lt;span class="nc"&gt;ChatController&lt;/span&gt; &lt;span class="o"&gt;{&lt;/span&gt;
    &lt;span class="kd"&gt;private&lt;/span&gt; &lt;span class="kd"&gt;final&lt;/span&gt; &lt;span class="nc"&gt;ChatClient&lt;/span&gt; &lt;span class="n"&gt;chatClient&lt;/span&gt;&lt;span class="o"&gt;;&lt;/span&gt;

    &lt;span class="kd"&gt;public&lt;/span&gt; &lt;span class="nf"&gt;ChatController&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="nc"&gt;ChatClient&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;Builder&lt;/span&gt; &lt;span class="n"&gt;chatClientBuilder&lt;/span&gt;&lt;span class="o"&gt;)&lt;/span&gt; &lt;span class="o"&gt;{&lt;/span&gt;
        &lt;span class="k"&gt;this&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;chatClient&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;chatClientBuilder&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;build&lt;/span&gt;&lt;span class="o"&gt;();&lt;/span&gt;
    &lt;span class="o"&gt;}&lt;/span&gt;

    &lt;span class="nd"&gt;@PostMapping&lt;/span&gt;
    &lt;span class="nc"&gt;GenerationResponse&lt;/span&gt; &lt;span class="nf"&gt;generation&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="nd"&gt;@RequestBody&lt;/span&gt; &lt;span class="nc"&gt;GenerationRequest&lt;/span&gt; &lt;span class="n"&gt;request&lt;/span&gt;&lt;span class="o"&gt;)&lt;/span&gt; &lt;span class="o"&gt;{&lt;/span&gt;
        &lt;span class="kt"&gt;var&lt;/span&gt; &lt;span class="n"&gt;modelContent&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;chatClient&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;prompt&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="n"&gt;request&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;userMessage&lt;/span&gt;&lt;span class="o"&gt;()).&lt;/span&gt;&lt;span class="na"&gt;call&lt;/span&gt;&lt;span class="o"&gt;().&lt;/span&gt;&lt;span class="na"&gt;content&lt;/span&gt;&lt;span class="o"&gt;();&lt;/span&gt;
        &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="k"&gt;new&lt;/span&gt; &lt;span class="nf"&gt;GenerationResponse&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="n"&gt;modelContent&lt;/span&gt;&lt;span class="o"&gt;);&lt;/span&gt;
    &lt;span class="o"&gt;}&lt;/span&gt;
&lt;span class="o"&gt;}&lt;/span&gt;

&lt;span class="kd"&gt;record&lt;/span&gt; &lt;span class="nf"&gt;GenerationRequest&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="nc"&gt;String&lt;/span&gt; &lt;span class="n"&gt;userMessage&lt;/span&gt;&lt;span class="o"&gt;)&lt;/span&gt; &lt;span class="o"&gt;{}&lt;/span&gt;

&lt;span class="kd"&gt;record&lt;/span&gt; &lt;span class="nf"&gt;GenerationResponse&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="nc"&gt;String&lt;/span&gt; &lt;span class="n"&gt;modelContent&lt;/span&gt;&lt;span class="o"&gt;)&lt;/span&gt; &lt;span class="o"&gt;{}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;That is a complete, working AI endpoint. Four steps carry the whole interaction:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;code&gt;prompt(request.userMessage())&lt;/code&gt;&amp;nbsp;starts the fluent chain with the user message.&lt;/li&gt;
&lt;li&gt;
&lt;code&gt;call()&lt;/code&gt;&amp;nbsp;sends the request to the model.&lt;/li&gt;
&lt;li&gt;
&lt;code&gt;content()&lt;/code&gt;&amp;nbsp;returns the response as a&amp;nbsp;&lt;code&gt;String&lt;/code&gt;.&lt;/li&gt;
&lt;li&gt;
&lt;code&gt;new GenerationResponse(modelContent)&lt;/code&gt;&amp;nbsp;wraps the model output in your response DTO.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Send a POST request and you get the model’s reply. The same&amp;nbsp;&lt;code&gt;ChatClient&lt;/code&gt;&amp;nbsp;shape works whether the model behind it comes from OpenAI, Anthropic, or runs locally. In this guide I will use a local model through LM Studio with an OpenAI-compatible API.&lt;/p&gt;

&lt;h2&gt;
  
  
  Setting up Spring AI
&lt;/h2&gt;

&lt;p&gt;To get that controller running you need the Spring AI BOM, the provider starter, an API key, and a few properties to wire them together.&lt;/p&gt;

&lt;p&gt;The starter artifacts follow a predictable pattern,&amp;nbsp;&lt;code&gt;spring-ai-starter-model-{provider}&lt;/code&gt;. For OpenAI:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight gradle"&gt;&lt;code&gt;&lt;span class="n"&gt;plugins&lt;/span&gt; &lt;span class="o"&gt;{&lt;/span&gt;  
    &lt;span class="n"&gt;id&lt;/span&gt; &lt;span class="s1"&gt;'java'&lt;/span&gt;  
    &lt;span class="n"&gt;id&lt;/span&gt; &lt;span class="s1"&gt;'org.springframework.boot'&lt;/span&gt; &lt;span class="n"&gt;version&lt;/span&gt; &lt;span class="s1"&gt;'4.1.0'&lt;/span&gt;  
    &lt;span class="n"&gt;id&lt;/span&gt; &lt;span class="s1"&gt;'io.spring.dependency-management'&lt;/span&gt; &lt;span class="n"&gt;version&lt;/span&gt; &lt;span class="s1"&gt;'1.1.7'&lt;/span&gt;  
&lt;span class="o"&gt;}&lt;/span&gt;

&lt;span class="k"&gt;repositories&lt;/span&gt; &lt;span class="o"&gt;{&lt;/span&gt;
    &lt;span class="n"&gt;mavenCentral&lt;/span&gt;&lt;span class="o"&gt;()&lt;/span&gt;
&lt;span class="o"&gt;}&lt;/span&gt;

&lt;span class="n"&gt;ext&lt;/span&gt; &lt;span class="o"&gt;{&lt;/span&gt;  
    &lt;span class="n"&gt;set&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="s1"&gt;'springAiVersion'&lt;/span&gt;&lt;span class="o"&gt;,&lt;/span&gt; &lt;span class="s2"&gt;"2.0.0-RC2"&lt;/span&gt;&lt;span class="o"&gt;)&lt;/span&gt;  
&lt;span class="o"&gt;}&lt;/span&gt;

&lt;span class="k"&gt;dependencies&lt;/span&gt; &lt;span class="o"&gt;{&lt;/span&gt;
    &lt;span class="n"&gt;implementation&lt;/span&gt; &lt;span class="s1"&gt;'org.springframework.ai:spring-ai-starter-model-openai'&lt;/span&gt;
&lt;span class="o"&gt;}&lt;/span&gt;

&lt;span class="n"&gt;dependencyManagement&lt;/span&gt; &lt;span class="o"&gt;{&lt;/span&gt;
    &lt;span class="n"&gt;imports&lt;/span&gt; &lt;span class="o"&gt;{&lt;/span&gt;
        &lt;span class="n"&gt;mavenBom&lt;/span&gt; &lt;span class="s2"&gt;"org.springframework.ai:spring-ai-bom:${springAiVersion}"&lt;/span&gt;
    &lt;span class="o"&gt;}&lt;/span&gt;
&lt;span class="o"&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The starter triggers the auto-configuration that hands you a ready&amp;nbsp;&lt;code&gt;ChatClient.Builder&lt;/code&gt;. Each provider reads its own properties. For an OpenAI-compatible API:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight properties"&gt;&lt;code&gt;&lt;span class="py"&gt;spring.ai.openai.api-key&lt;/span&gt;&lt;span class="p"&gt;=&lt;/span&gt;&lt;span class="s"&gt;${OPENAI_API_KEY:local-model}  &lt;/span&gt;
&lt;span class="py"&gt;spring.ai.openai.base-url&lt;/span&gt;&lt;span class="p"&gt;=&lt;/span&gt;&lt;span class="s"&gt;${OPENAI_BASE_URL:http://localhost:1234/v1}  &lt;/span&gt;
&lt;span class="py"&gt;spring.ai.openai.chat.model&lt;/span&gt;&lt;span class="p"&gt;=&lt;/span&gt;&lt;span class="s"&gt;${OPENAI_MODEL:nvidia/nemotron-3-nano-4b}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Keep the real key in an environment variable rather than in&amp;nbsp;&lt;code&gt;application.properties&lt;/code&gt;; for local models the provided placeholder is enough.&lt;/p&gt;

&lt;p&gt;For any Spring setup from scratch, I highly recommend using &lt;a href="https://start.spring.io" rel="noopener noreferrer"&gt;Spring Initializr&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;Full demo project you can find here: &lt;a href="https://github.com/NordCoderd/spring-ai-demo-project" rel="noopener noreferrer"&gt;spring-ai-demo-project&lt;/a&gt;&lt;/p&gt;

&lt;h2&gt;
  
  
  Useful building blocks in Spring AI
&lt;/h2&gt;

&lt;p&gt;A single chat call is just the beginning. Teams adopt Spring AI for the building blocks that come after chat.&lt;/p&gt;

&lt;p&gt;We will build one thing through them all: a personal assistant. It starts as a plain chat call. By the end of this section it answers from your own notes, remembers the conversation, reads your live calendar, returns a typed object, and exposes that calendar lookup to other AI agents. Each block adds a few lines to the same assistant.&lt;/p&gt;

&lt;p&gt;Here is the starting point. A&amp;nbsp;&lt;code&gt;@Service&lt;/code&gt;&amp;nbsp;that wraps a&amp;nbsp;&lt;code&gt;ChatClient&lt;/code&gt;:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight java"&gt;&lt;code&gt;&lt;span class="nd"&gt;@Service&lt;/span&gt;
&lt;span class="kd"&gt;public&lt;/span&gt; &lt;span class="kd"&gt;class&lt;/span&gt; &lt;span class="nc"&gt;Assistant&lt;/span&gt; &lt;span class="o"&gt;{&lt;/span&gt;

    &lt;span class="kd"&gt;private&lt;/span&gt; &lt;span class="kd"&gt;final&lt;/span&gt; &lt;span class="nc"&gt;ChatClient&lt;/span&gt; &lt;span class="n"&gt;chatClient&lt;/span&gt;&lt;span class="o"&gt;;&lt;/span&gt;

    &lt;span class="nc"&gt;Assistant&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="nc"&gt;ChatClient&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;Builder&lt;/span&gt; &lt;span class="n"&gt;builder&lt;/span&gt;&lt;span class="o"&gt;)&lt;/span&gt; &lt;span class="o"&gt;{&lt;/span&gt;
        &lt;span class="k"&gt;this&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;chatClient&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;builder&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;build&lt;/span&gt;&lt;span class="o"&gt;();&lt;/span&gt;
    &lt;span class="o"&gt;}&lt;/span&gt;

    &lt;span class="kd"&gt;public&lt;/span&gt; &lt;span class="nc"&gt;String&lt;/span&gt; &lt;span class="nf"&gt;ask&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="nc"&gt;String&lt;/span&gt; &lt;span class="n"&gt;question&lt;/span&gt;&lt;span class="o"&gt;)&lt;/span&gt; &lt;span class="o"&gt;{&lt;/span&gt;
        &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="n"&gt;chatClient&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;prompt&lt;/span&gt;&lt;span class="o"&gt;()&lt;/span&gt;
            &lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;user&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="n"&gt;question&lt;/span&gt;&lt;span class="o"&gt;)&lt;/span&gt;
            &lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;call&lt;/span&gt;&lt;span class="o"&gt;()&lt;/span&gt;
            &lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;content&lt;/span&gt;&lt;span class="o"&gt;();&lt;/span&gt;
    &lt;span class="o"&gt;}&lt;/span&gt;
&lt;span class="o"&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;That works, but the model has no persona and no memory. Let me fix that one block at a time.&lt;/p&gt;

&lt;h3&gt;
  
  
  System prompts
&lt;/h3&gt;

&lt;p&gt;A prompt is more than the user’s text. It carries two kinds of message: a system prompt that sets the rules and persona, and the user message that holds the question. Spring AI builds these as typed objects, so you set them with methods instead of gluing strings together.&lt;/p&gt;

&lt;p&gt;Give the assistant a system prompt so it behaves like a personal assistant. You set it once, as a default, when you build the client:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight java"&gt;&lt;code&gt;&lt;span class="nc"&gt;Assistant&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="nc"&gt;ChatClient&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;Builder&lt;/span&gt; &lt;span class="n"&gt;builder&lt;/span&gt;&lt;span class="o"&gt;)&lt;/span&gt; &lt;span class="o"&gt;{&lt;/span&gt;
    &lt;span class="k"&gt;this&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;chatClient&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;builder&lt;/span&gt;
        &lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;defaultSystem&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="sh"&gt;"""
            You are my personal assistant.
            Answer in two or three sentences. Be direct and friendly.
            If you do not know, say so instead of guessing.
            """&lt;/span&gt;&lt;span class="o"&gt;)&lt;/span&gt;
        &lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;build&lt;/span&gt;&lt;span class="o"&gt;();&lt;/span&gt;
&lt;span class="o"&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Now every call carries that system prompt in front of your question. The model receives its role before it reads a single word you type.&amp;nbsp;&lt;code&gt;defaultSystem&lt;/code&gt;&amp;nbsp;sets it for the whole client; you can also set a per-call&amp;nbsp;&lt;code&gt;.system(...)&lt;/code&gt;&amp;nbsp;when one request needs different rules.&lt;/p&gt;

&lt;h3&gt;
  
  
  Advisors
&lt;/h3&gt;

&lt;p&gt;An advisor is a component that intercepts data on the way to the model and on the way back, so you can attach cross-cutting behavior without touching your call code. The Advisors API encapsulates what the docs call “recurring Generative AI patterns.” The two features you will reach for first, memory and retrieval, are both advisors. That is the payoff: register an advisor and the behavior is there.&lt;/p&gt;

&lt;p&gt;Start with memory. Out of the box, the assistant forgets everything between calls. Ask “what is on my calendar today?” then “move the first one to 17:00” and the second question has lost track of what “the first one” is.&amp;nbsp;&lt;code&gt;MessageChatMemoryAdvisor&lt;/code&gt;&amp;nbsp;fixes that by replaying recent turns into each prompt.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight java"&gt;&lt;code&gt;&lt;span class="nc"&gt;Assistant&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="nc"&gt;ChatClient&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;Builder&lt;/span&gt; &lt;span class="n"&gt;builder&lt;/span&gt;&lt;span class="o"&gt;)&lt;/span&gt; &lt;span class="o"&gt;{&lt;/span&gt;
    &lt;span class="nc"&gt;ChatMemory&lt;/span&gt; &lt;span class="n"&gt;chatMemory&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nc"&gt;MessageWindowChatMemory&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;builder&lt;/span&gt;&lt;span class="o"&gt;().&lt;/span&gt;&lt;span class="na"&gt;build&lt;/span&gt;&lt;span class="o"&gt;();&lt;/span&gt;

    &lt;span class="k"&gt;this&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;chatClient&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;builder&lt;/span&gt;
        &lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;defaultSystem&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="s"&gt;"You are my personal assistant..."&lt;/span&gt;&lt;span class="o"&gt;)&lt;/span&gt;
        &lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;defaultAdvisors&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="nc"&gt;MessageChatMemoryAdvisor&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;builder&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="n"&gt;chatMemory&lt;/span&gt;&lt;span class="o"&gt;).&lt;/span&gt;&lt;span class="na"&gt;build&lt;/span&gt;&lt;span class="o"&gt;())&lt;/span&gt;
        &lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;build&lt;/span&gt;&lt;span class="o"&gt;();&lt;/span&gt;
&lt;span class="o"&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The memory advisor needs to know which conversation a question belongs to, so separate chats never bleed into each other. You pass that id per call with&amp;nbsp;&lt;code&gt;ChatMemory.CONVERSATION_ID&lt;/code&gt;:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight java"&gt;&lt;code&gt;&lt;span class="nc"&gt;String&lt;/span&gt; &lt;span class="nf"&gt;ask&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="nc"&gt;String&lt;/span&gt; &lt;span class="n"&gt;conversationId&lt;/span&gt;&lt;span class="o"&gt;,&lt;/span&gt; &lt;span class="nc"&gt;String&lt;/span&gt; &lt;span class="n"&gt;question&lt;/span&gt;&lt;span class="o"&gt;)&lt;/span&gt; &lt;span class="o"&gt;{&lt;/span&gt;
    &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="n"&gt;chatClient&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;prompt&lt;/span&gt;&lt;span class="o"&gt;()&lt;/span&gt;
        &lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;user&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="n"&gt;question&lt;/span&gt;&lt;span class="o"&gt;)&lt;/span&gt;
        &lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;advisors&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="n"&gt;a&lt;/span&gt; &lt;span class="o"&gt;-&amp;gt;&lt;/span&gt; &lt;span class="n"&gt;a&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;param&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="nc"&gt;ChatMemory&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;CONVERSATION_ID&lt;/span&gt;&lt;span class="o"&gt;,&lt;/span&gt; &lt;span class="n"&gt;conversationId&lt;/span&gt;&lt;span class="o"&gt;))&lt;/span&gt;
        &lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;call&lt;/span&gt;&lt;span class="o"&gt;()&lt;/span&gt;
        &lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;content&lt;/span&gt;&lt;span class="o"&gt;();&lt;/span&gt;
&lt;span class="o"&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;code&gt;MessageWindowChatMemory&lt;/code&gt;&amp;nbsp;keeps a rolling window of recent messages (20 by default), so the prompt does not grow without bound. The advisor requires the conversation id: leave it out and it throws at runtime. Now the assistant remembers, but it still only knows the base model’s training data. It has never read a single note about you. That is the next block.&lt;/p&gt;

&lt;h3&gt;
  
  
  Vector stores and embeddings
&lt;/h3&gt;

&lt;p&gt;An embedding is a list of numbers that captures what a piece of text is about, so a model can search by meaning rather than exact words. A vector store holds those embeddings and finds the nearest ones to a query.&lt;/p&gt;

&lt;p&gt;To answer from your own content, the assistant first has to store that content as embeddings. Two notes about travel end up close together in that number space, even if they share no words.&lt;/p&gt;

&lt;p&gt;Spring AI gives you one&amp;nbsp;&lt;code&gt;VectorStore&lt;/code&gt;&amp;nbsp;interface across more than twenty backends, including PostgreSQL with PGvector and Redis. The same code runs against any of them.&lt;/p&gt;

&lt;p&gt;For embeddings and storage, I will use PgVector with the&amp;nbsp;&lt;code&gt;text-embedding-nomic-embed-text-v1.5&lt;/code&gt;&amp;nbsp;local model. A real database makes the demo match what you would deploy.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight properties"&gt;&lt;code&gt;&lt;span class="py"&gt;spring.ai.openai.embedding.api-key&lt;/span&gt;&lt;span class="p"&gt;=&lt;/span&gt;&lt;span class="s"&gt;${OPENAI_API_KEY:local-model}  &lt;/span&gt;
&lt;span class="py"&gt;spring.ai.openai.embedding.base-url&lt;/span&gt;&lt;span class="p"&gt;=&lt;/span&gt;&lt;span class="s"&gt;${OPENAI_EMBEDDING_BASE_URL:http://localhost:1234/v1}  &lt;/span&gt;
&lt;span class="py"&gt;spring.ai.openai.embedding.model&lt;/span&gt;&lt;span class="p"&gt;=&lt;/span&gt;&lt;span class="s"&gt;${OPENAI_EMBEDDING_MODEL:text-embedding-nomic-embed-text-v1.5}  &lt;/span&gt;
&lt;span class="py"&gt;spring.ai.vectorstore.pgvector.initialize-schema&lt;/span&gt;&lt;span class="p"&gt;=&lt;/span&gt;&lt;span class="s"&gt;true&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;PgVector comes in through its own starter,&amp;nbsp;&lt;code&gt;spring-ai-starter-vector-store-pgvector&lt;/code&gt;, plus a running PostgreSQL;&amp;nbsp;&lt;code&gt;initialize-schema=true&lt;/code&gt;&amp;nbsp;creates the vector table at startup.&lt;/p&gt;

&lt;p&gt;Load your notes once at startup. Each note becomes a&amp;nbsp;&lt;code&gt;Document&lt;/code&gt;, and&amp;nbsp;&lt;code&gt;vectorStore.add(...)&lt;/code&gt;&amp;nbsp;turns it into an embedding and stores it:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight java"&gt;&lt;code&gt;&lt;span class="nd"&gt;@Component&lt;/span&gt;
&lt;span class="kd"&gt;class&lt;/span&gt; &lt;span class="nc"&gt;NotesLoader&lt;/span&gt; &lt;span class="o"&gt;{&lt;/span&gt;

    &lt;span class="nc"&gt;NotesLoader&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="nc"&gt;VectorStore&lt;/span&gt; &lt;span class="n"&gt;vectorStore&lt;/span&gt;&lt;span class="o"&gt;)&lt;/span&gt; &lt;span class="o"&gt;{&lt;/span&gt;
        &lt;span class="n"&gt;vectorStore&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;add&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="nc"&gt;List&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;of&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;
            &lt;span class="k"&gt;new&lt;/span&gt; &lt;span class="nf"&gt;Document&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="s"&gt;"My name is Dima, a short name for Dmitry."&lt;/span&gt;&lt;span class="o"&gt;),&lt;/span&gt;
            &lt;span class="k"&gt;new&lt;/span&gt; &lt;span class="nf"&gt;Document&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="s"&gt;"I love jelly beans, so make sure I have them in the fridge."&lt;/span&gt;&lt;span class="o"&gt;),&lt;/span&gt;
            &lt;span class="k"&gt;new&lt;/span&gt; &lt;span class="nf"&gt;Document&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="s"&gt;"I prefer window seats on flights with extra leg room."&lt;/span&gt;&lt;span class="o"&gt;),&lt;/span&gt;
            &lt;span class="k"&gt;new&lt;/span&gt; &lt;span class="nf"&gt;Document&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="s"&gt;"My wedding anniversary is on 30 April."&lt;/span&gt;&lt;span class="o"&gt;),&lt;/span&gt;
            &lt;span class="k"&gt;new&lt;/span&gt; &lt;span class="nf"&gt;Document&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="s"&gt;"I go to the gym on Monday and Thursday."&lt;/span&gt;&lt;span class="o"&gt;)&lt;/span&gt;
        &lt;span class="o"&gt;));&lt;/span&gt;
    &lt;span class="o"&gt;}&lt;/span&gt;
&lt;span class="o"&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;You never call an embedding model by hand here.&amp;nbsp;&lt;code&gt;add&lt;/code&gt;&amp;nbsp;uses the auto-configured&amp;nbsp;&lt;code&gt;EmbeddingModel&lt;/code&gt;&amp;nbsp;to vectorize each note for you. The store now holds five searchable facts about you. The next block puts them in front of the model.&lt;/p&gt;

&lt;h3&gt;
  
  
  Using RAG with Spring AI
&lt;/h3&gt;

&lt;p&gt;RAG is how you get a model to answer from your data instead of guessing. The flow is: take the question, search the vector store for the most relevant notes, paste them into the prompt, and let the model answer grounded in that text. The model can still draw on its own training when the retrieved notes do not cover the question, so the system prompt you set earlier matters: “If you do not know, say so instead of guessing” is what steers it away from invention.&lt;/p&gt;

&lt;p&gt;Spring AI ships this as an advisor too:&amp;nbsp;&lt;code&gt;QuestionAnswerAdvisor&lt;/code&gt;. Hand it the vector store and add it to the client. It runs the search and injects the matches on every call, so your&amp;nbsp;&lt;code&gt;ask&lt;/code&gt;&amp;nbsp;method does not change:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight java"&gt;&lt;code&gt;&lt;span class="nc"&gt;Assistant&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="nc"&gt;ChatClient&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;Builder&lt;/span&gt; &lt;span class="n"&gt;builder&lt;/span&gt;&lt;span class="o"&gt;,&lt;/span&gt; &lt;span class="nc"&gt;VectorStore&lt;/span&gt; &lt;span class="n"&gt;vectorStore&lt;/span&gt;&lt;span class="o"&gt;)&lt;/span&gt; &lt;span class="o"&gt;{&lt;/span&gt;  
    &lt;span class="kt"&gt;var&lt;/span&gt; &lt;span class="n"&gt;chatMemory&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nc"&gt;MessageWindowChatMemory&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;builder&lt;/span&gt;&lt;span class="o"&gt;().&lt;/span&gt;&lt;span class="na"&gt;build&lt;/span&gt;&lt;span class="o"&gt;();&lt;/span&gt;  
    &lt;span class="kt"&gt;var&lt;/span&gt; &lt;span class="n"&gt;memoryAdvisor&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nc"&gt;MessageChatMemoryAdvisor&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;builder&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="n"&gt;chatMemory&lt;/span&gt;&lt;span class="o"&gt;).&lt;/span&gt;&lt;span class="na"&gt;build&lt;/span&gt;&lt;span class="o"&gt;();&lt;/span&gt;  
    &lt;span class="kt"&gt;var&lt;/span&gt; &lt;span class="n"&gt;questionAnswerAdvisor&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nc"&gt;QuestionAnswerAdvisor&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;builder&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="n"&gt;vectorStore&lt;/span&gt;&lt;span class="o"&gt;).&lt;/span&gt;&lt;span class="na"&gt;build&lt;/span&gt;&lt;span class="o"&gt;();&lt;/span&gt;  

    &lt;span class="k"&gt;this&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;chatClient&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;builder&lt;/span&gt;  
            &lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;defaultSystem&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="n"&gt;systemPrompt&lt;/span&gt;&lt;span class="o"&gt;)&lt;/span&gt;  
            &lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;defaultAdvisors&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="n"&gt;memoryAdvisor&lt;/span&gt;&lt;span class="o"&gt;,&lt;/span&gt; &lt;span class="n"&gt;questionAnswerAdvisor&lt;/span&gt;&lt;span class="o"&gt;)&lt;/span&gt;  
            &lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;build&lt;/span&gt;&lt;span class="o"&gt;();&lt;/span&gt;  
&lt;span class="o"&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Ask “what seat should you book me on the next flight?” and the advisor finds the window-seat note and injects it. The model then answers from your preference rather than guessing. You can tune the search with a&amp;nbsp;&lt;code&gt;SearchRequest&lt;/code&gt;, for example to set a similarity floor and cap the number of notes:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight java"&gt;&lt;code&gt;&lt;span class="nc"&gt;QuestionAnswerAdvisor&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;builder&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="n"&gt;vectorStore&lt;/span&gt;&lt;span class="o"&gt;)&lt;/span&gt;
    &lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;searchRequest&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="nc"&gt;SearchRequest&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;builder&lt;/span&gt;&lt;span class="o"&gt;()&lt;/span&gt;
        &lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;similarityThreshold&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="mf"&gt;0.7&lt;/span&gt;&lt;span class="o"&gt;)&lt;/span&gt;
        &lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;topK&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;4&lt;/span&gt;&lt;span class="o"&gt;)&lt;/span&gt;
        &lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;build&lt;/span&gt;&lt;span class="o"&gt;())&lt;/span&gt;
    &lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;build&lt;/span&gt;&lt;span class="o"&gt;();&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;code&gt;topK&lt;/code&gt;&amp;nbsp;is how many notes to pull, and&amp;nbsp;&lt;code&gt;similarityThreshold&lt;/code&gt;&amp;nbsp;drops weak matches to keep unrelated notes out of the prompt. The assistant now has your notes in context for each answer. But “what is on my calendar today?” is not in any note. That answer changes by the hour, and the model needs to fetch it live.&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;&lt;strong&gt;Found this useful?&lt;/strong&gt; Follow me on social media to stay updated.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://t.me/protsenko_dev" rel="noopener noreferrer"&gt;Telegram&lt;/a&gt; · &lt;a href="https://www.linkedin.com/in/protsenkodev/" rel="noopener noreferrer"&gt;LinkedIn&lt;/a&gt;&lt;/p&gt;
&lt;/blockquote&gt;

&lt;h3&gt;
  
  
  Tool calling
&lt;/h3&gt;

&lt;p&gt;Tool calling (also called function calling) lets the model request the execution of Java methods you register, so it can reach live data beyond its training. You write a normal method, mark it with&amp;nbsp;&lt;code&gt;@Tool&lt;/code&gt;, and the model decides when to call it. The model never runs your code itself; it asks Spring AI to run the method and hands back the result. Use it when the answer changes by the hour, like a calendar or a price feed.&lt;/p&gt;

&lt;p&gt;Give the assistant a calendar lookup. In real code the method hits your calendar API; here it returns a canned answer:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight java"&gt;&lt;code&gt;&lt;span class="nd"&gt;@Component&lt;/span&gt;
&lt;span class="kd"&gt;class&lt;/span&gt; &lt;span class="nc"&gt;CalendarTools&lt;/span&gt; &lt;span class="o"&gt;{&lt;/span&gt;

    &lt;span class="nd"&gt;@Tool&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="n"&gt;description&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="s"&gt;"Get the agenda for a given day from the user's calendar"&lt;/span&gt;&lt;span class="o"&gt;)&lt;/span&gt;
    &lt;span class="kd"&gt;public&lt;/span&gt; &lt;span class="nc"&gt;String&lt;/span&gt; &lt;span class="nf"&gt;getAgenda&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;
            &lt;span class="nd"&gt;@ToolParam&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="n"&gt;description&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="s"&gt;"The day in ISO format, for example 2026-06-11"&lt;/span&gt;&lt;span class="o"&gt;)&lt;/span&gt; &lt;span class="nc"&gt;String&lt;/span&gt; &lt;span class="n"&gt;day&lt;/span&gt;&lt;span class="o"&gt;)&lt;/span&gt; &lt;span class="o"&gt;{&lt;/span&gt;
        &lt;span class="c1"&gt;// real code would query your calendar API&lt;/span&gt;
        &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="s"&gt;"On "&lt;/span&gt; &lt;span class="o"&gt;+&lt;/span&gt; &lt;span class="n"&gt;day&lt;/span&gt; &lt;span class="o"&gt;+&lt;/span&gt; &lt;span class="s"&gt;": standup at 10:00, dentist at 16:00."&lt;/span&gt;&lt;span class="o"&gt;;&lt;/span&gt;
    &lt;span class="o"&gt;}&lt;/span&gt;

    &lt;span class="nd"&gt;@Tool&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="n"&gt;description&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="s"&gt;"Fetch current (today) date in ISO format"&lt;/span&gt;&lt;span class="o"&gt;)&lt;/span&gt;
    &lt;span class="kd"&gt;public&lt;/span&gt; &lt;span class="nc"&gt;String&lt;/span&gt; &lt;span class="nf"&gt;getCurrentDate&lt;/span&gt;&lt;span class="o"&gt;()&lt;/span&gt; &lt;span class="o"&gt;{&lt;/span&gt;
        &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="nc"&gt;LocalDate&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;now&lt;/span&gt;&lt;span class="o"&gt;().&lt;/span&gt;&lt;span class="na"&gt;toString&lt;/span&gt;&lt;span class="o"&gt;();&lt;/span&gt;
    &lt;span class="o"&gt;}&lt;/span&gt;
&lt;span class="o"&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Register the tool on the call with&amp;nbsp;&lt;code&gt;.tools(...)&lt;/code&gt;. The model reads the&amp;nbsp;&lt;code&gt;@Tool&lt;/code&gt;&amp;nbsp;description and, if it decides the question calls for it, requests execution with the day it parsed from the question:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight java"&gt;&lt;code&gt;&lt;span class="nc"&gt;String&lt;/span&gt; &lt;span class="nf"&gt;ask&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="nc"&gt;String&lt;/span&gt; &lt;span class="n"&gt;conversationId&lt;/span&gt;&lt;span class="o"&gt;,&lt;/span&gt; &lt;span class="nc"&gt;String&lt;/span&gt; &lt;span class="n"&gt;question&lt;/span&gt;&lt;span class="o"&gt;,&lt;/span&gt; &lt;span class="nc"&gt;CalendarTools&lt;/span&gt; &lt;span class="n"&gt;calendarTools&lt;/span&gt;&lt;span class="o"&gt;)&lt;/span&gt; &lt;span class="o"&gt;{&lt;/span&gt;
    &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="n"&gt;chatClient&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;prompt&lt;/span&gt;&lt;span class="o"&gt;()&lt;/span&gt;
        &lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;user&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="n"&gt;question&lt;/span&gt;&lt;span class="o"&gt;)&lt;/span&gt;
        &lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;advisors&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="n"&gt;a&lt;/span&gt; &lt;span class="o"&gt;-&amp;gt;&lt;/span&gt; &lt;span class="n"&gt;a&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;param&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="nc"&gt;ChatMemory&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;CONVERSATION_ID&lt;/span&gt;&lt;span class="o"&gt;,&lt;/span&gt; &lt;span class="n"&gt;conversationId&lt;/span&gt;&lt;span class="o"&gt;))&lt;/span&gt;
        &lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;tools&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="n"&gt;calendarTools&lt;/span&gt;&lt;span class="o"&gt;)&lt;/span&gt;
        &lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;call&lt;/span&gt;&lt;span class="o"&gt;()&lt;/span&gt;
        &lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;content&lt;/span&gt;&lt;span class="o"&gt;();&lt;/span&gt;
&lt;span class="o"&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;A question like “what is on my calendar today?” can lead the model to call&amp;nbsp;&lt;code&gt;getCurrentDate&lt;/code&gt;&amp;nbsp;for today’s date and then&amp;nbsp;&lt;code&gt;getAgenda&lt;/code&gt;. It reads the result and replies in plain language.&amp;nbsp;&lt;code&gt;@ToolParam&lt;/code&gt;&amp;nbsp;descriptions tell the model what to put in each argument. The assistant can answer from your notes and from live data. The last gap is the shape of the answer.&lt;/p&gt;

&lt;h3&gt;
  
  
  Structured output
&lt;/h3&gt;

&lt;p&gt;Structured output maps the model’s response straight onto a Java record, so you get a typed object instead of a free-text string. Free text reads well to a human and badly to code. If another part of your system needs to route the answer or flag it, parsing a paragraph is fragile.&lt;/p&gt;

&lt;p&gt;Declare the shape you want as a record, then ask for it with&amp;nbsp;&lt;code&gt;.entity(...)&lt;/code&gt;&amp;nbsp;instead of&amp;nbsp;&lt;code&gt;.content()&lt;/code&gt;:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight java"&gt;&lt;code&gt;&lt;span class="kd"&gt;record&lt;/span&gt; &lt;span class="nf"&gt;AssistantReply&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="nc"&gt;String&lt;/span&gt; &lt;span class="n"&gt;answer&lt;/span&gt;&lt;span class="o"&gt;,&lt;/span&gt; &lt;span class="nc"&gt;String&lt;/span&gt; &lt;span class="n"&gt;category&lt;/span&gt;&lt;span class="o"&gt;,&lt;/span&gt; &lt;span class="kt"&gt;boolean&lt;/span&gt; &lt;span class="n"&gt;needsFollowUp&lt;/span&gt;&lt;span class="o"&gt;)&lt;/span&gt; &lt;span class="o"&gt;{}&lt;/span&gt;

&lt;span class="nc"&gt;AssistantReply&lt;/span&gt; &lt;span class="nf"&gt;reply&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="nc"&gt;String&lt;/span&gt; &lt;span class="n"&gt;conversationId&lt;/span&gt;&lt;span class="o"&gt;,&lt;/span&gt; &lt;span class="nc"&gt;String&lt;/span&gt; &lt;span class="n"&gt;question&lt;/span&gt;&lt;span class="o"&gt;,&lt;/span&gt; &lt;span class="nc"&gt;CalendarTools&lt;/span&gt; &lt;span class="n"&gt;calendarTools&lt;/span&gt;&lt;span class="o"&gt;)&lt;/span&gt; &lt;span class="o"&gt;{&lt;/span&gt;
    &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="n"&gt;chatClient&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;prompt&lt;/span&gt;&lt;span class="o"&gt;()&lt;/span&gt;
        &lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;user&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="n"&gt;question&lt;/span&gt;&lt;span class="o"&gt;)&lt;/span&gt;
        &lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;advisors&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="n"&gt;a&lt;/span&gt; &lt;span class="o"&gt;-&amp;gt;&lt;/span&gt; &lt;span class="n"&gt;a&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;param&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="nc"&gt;ChatMemory&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;CONVERSATION_ID&lt;/span&gt;&lt;span class="o"&gt;,&lt;/span&gt; &lt;span class="n"&gt;conversationId&lt;/span&gt;&lt;span class="o"&gt;))&lt;/span&gt;
        &lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;tools&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="n"&gt;calendarTools&lt;/span&gt;&lt;span class="o"&gt;)&lt;/span&gt;
        &lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;call&lt;/span&gt;&lt;span class="o"&gt;()&lt;/span&gt;
        &lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;entity&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="nc"&gt;AssistantReply&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;class&lt;/span&gt;&lt;span class="o"&gt;);&lt;/span&gt;
&lt;span class="o"&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Spring AI sends a format instruction that requests JSON shaped like&amp;nbsp;&lt;code&gt;AssistantReply&lt;/code&gt;, then converts the response back into the record. Now you can act on the result in code: route by&amp;nbsp;&lt;code&gt;category&lt;/code&gt;, or schedule a reminder when&amp;nbsp;&lt;code&gt;needsFollowUp&lt;/code&gt;&amp;nbsp;is true. The same assistant that answers in prose for a chat window returns a typed object for the rest of your app.&lt;/p&gt;

&lt;h3&gt;
  
  
  Model Context Protocol (MCP)
&lt;/h3&gt;

&lt;p&gt;MCP is the newer, fast-rising piece, an open protocol that connects AI applications to external tools and data sources in a standard way. Spring AI provides both client and server Boot starters. With the server starter, a Spring app exposes its own tools so any MCP-aware agent (an IDE assistant, a desktop AI app, another service) can call them over a standard protocol.&lt;/p&gt;

&lt;p&gt;You already wrote a tool worth sharing:&amp;nbsp;&lt;code&gt;getAgenda&lt;/code&gt;. Expose it as an MCP server and an outside agent can read your calendar without ever touching your REST API. Add the server starter:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight gradle"&gt;&lt;code&gt;&lt;span class="n"&gt;implementation&lt;/span&gt; &lt;span class="s1"&gt;'org.springframework.ai:spring-ai-starter-mcp-server-webmvc'&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Then publish the same&amp;nbsp;&lt;code&gt;CalendarTools&lt;/code&gt;&amp;nbsp;as MCP tools with a&amp;nbsp;&lt;code&gt;ToolCallbackProvider&lt;/code&gt;&amp;nbsp;bean. No new tool code; you reuse the class from the tool-calling block:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight java"&gt;&lt;code&gt;&lt;span class="nd"&gt;@Configuration&lt;/span&gt;  
&lt;span class="kd"&gt;public&lt;/span&gt; &lt;span class="kd"&gt;class&lt;/span&gt; &lt;span class="nc"&gt;McpCalendarToolsConfiguration&lt;/span&gt; &lt;span class="o"&gt;{&lt;/span&gt;  
    &lt;span class="nd"&gt;@Bean&lt;/span&gt;  
    &lt;span class="kd"&gt;public&lt;/span&gt; &lt;span class="nc"&gt;ToolCallbackProvider&lt;/span&gt; &lt;span class="nf"&gt;toolCallbackProvider&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="nc"&gt;CalendarTools&lt;/span&gt; &lt;span class="n"&gt;calendarTools&lt;/span&gt;&lt;span class="o"&gt;)&lt;/span&gt; &lt;span class="o"&gt;{&lt;/span&gt;  
        &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="nc"&gt;MethodToolCallbackProvider&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;builder&lt;/span&gt;&lt;span class="o"&gt;()&lt;/span&gt;  
                &lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;toolObjects&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="n"&gt;calendarTools&lt;/span&gt;&lt;span class="o"&gt;)&lt;/span&gt;  
                &lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;build&lt;/span&gt;&lt;span class="o"&gt;();&lt;/span&gt;  
    &lt;span class="o"&gt;}&lt;/span&gt;  
&lt;span class="o"&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Optionally, give the server a name in&amp;nbsp;&lt;code&gt;application.properties&lt;/code&gt;:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight properties"&gt;&lt;code&gt;&lt;span class="py"&gt;spring.ai.mcp.server.name&lt;/span&gt;&lt;span class="p"&gt;=&lt;/span&gt;&lt;span class="s"&gt;mcp-server-demo-ai  &lt;/span&gt;
&lt;span class="py"&gt;spring.ai.mcp.server.version&lt;/span&gt;&lt;span class="p"&gt;=&lt;/span&gt;&lt;span class="s"&gt;1.0.0&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The same&amp;nbsp;&lt;code&gt;@Tool&lt;/code&gt;&amp;nbsp;method now serves two callers: your own assistant through&amp;nbsp;&lt;code&gt;.tools(...)&lt;/code&gt;, and any external agent through MCP. That reuse is the point of the protocol. If you file one term away from this post, make it this one.&lt;/p&gt;

&lt;p&gt;The starter speaks the SSE protocol by default. Switch it to streamable HTTP, and the server listens on the&amp;nbsp;&lt;code&gt;/mcp&lt;/code&gt;&amp;nbsp;path; override the path with the second property:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight properties"&gt;&lt;code&gt;&lt;span class="py"&gt;spring.ai.mcp.server.protocol&lt;/span&gt;&lt;span class="p"&gt;=&lt;/span&gt;&lt;span class="s"&gt;STREAMABLE&lt;/span&gt;
&lt;span class="py"&gt;spring.ai.mcp.server.streamable-http.mcp-endpoint&lt;/span&gt;&lt;span class="p"&gt;=&lt;/span&gt;&lt;span class="s"&gt;/mcp&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h3&gt;
  
  
  The supporting cast
&lt;/h3&gt;

&lt;p&gt;A few more pieces round out the framework, and you will meet them once the assistant goes past a demo. An ETL pipeline reads real documents (PDFs, web pages) and chunks them before they reach the vector store, so you are not hand-typing notes. Model evaluation utilities check generated content and help guard against hallucinated responses.&lt;/p&gt;

&lt;p&gt;That is the whole assistant. It started as one chat call and grew, a few lines at a time, into something that knows your notes, remembers the conversation, reads live data, and returns structured output.&lt;/p&gt;

&lt;h2&gt;
  
  
  Where to go next with Spring AI
&lt;/h2&gt;

&lt;p&gt;You now have the map. Spring AI is the Spring-native layer between your Java app and AI models, built on portability and the same dependency-injection style you already use. The&amp;nbsp;&lt;code&gt;ChatClient&lt;/code&gt;&amp;nbsp;gets you a first response in minutes. Prompts, advisors, RAG, vector stores, tool calling, structured output, and MCP are the rooms you explore after that.&lt;/p&gt;

&lt;p&gt;A learning path that works: get the&amp;nbsp;&lt;code&gt;/api/chat&lt;/code&gt;&amp;nbsp;endpoint returning a reply, point it at a local model, then add structured output so the response comes back as a typed object. After that, try a small RAG example over a handful of your own documents. Each step adds a dependency and a few lines of Spring AI code.&lt;/p&gt;

&lt;p&gt;Do you use AI in your development workflow? Read my latest: &lt;a href="https://protsenko.dev/ai-driven-development-workflow-guard-rails/" rel="noopener noreferrer"&gt;AI Coding Workflow: TDD, Reviews, and Guardrails&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Next step: &lt;a href="https://protsenko.dev/spring-ai-rag-example-index-source-code-with-pgvector/" rel="noopener noreferrer"&gt;Spring AI RAG example: index source code with PgVector&lt;/a&gt;.&lt;/strong&gt;&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;&lt;strong&gt;Found this useful?&lt;/strong&gt; Follow me on social media to stay updated.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://t.me/protsenko_dev" rel="noopener noreferrer"&gt;Telegram&lt;/a&gt; · &lt;a href="https://www.linkedin.com/in/protsenkodev/" rel="noopener noreferrer"&gt;LinkedIn&lt;/a&gt;&lt;/p&gt;
&lt;/blockquote&gt;

</description>
      <category>java</category>
      <category>spring</category>
      <category>ai</category>
      <category>beginners</category>
    </item>
    <item>
      <title>Spring Data JPA Transactions and Queries</title>
      <dc:creator>Dmitry Protsenko</dc:creator>
      <pubDate>Fri, 06 Nov 2026 15:00:00 +0000</pubDate>
      <link>https://dev.to/protsenko/spring-data-jpa-transactions-and-queries-3bdd</link>
      <guid>https://dev.to/protsenko/spring-data-jpa-transactions-and-queries-3bdd</guid>
      <description>&lt;p&gt;The last but not least part of my series of articles on Spring Data JPA guide, employing best practices to help you keep the code base clean and avoid common mistakes.&lt;/p&gt;

&lt;p&gt;This guide was initially written based on observations from a huge legacy project, and to promote good practices, I collected all the problems, systematized them, and shared them with my former colleagues. The guide is updated and completely rewritten to utilize the latest features of Spring Data JPA.&lt;/p&gt;

&lt;p&gt;Other articles in the series:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;a href="https://protsenko.dev/spring-data-jpa-best-practices-entity-design-guide/" rel="noopener noreferrer"&gt;Spring Data JPA Best Practices: Entity Design Guide&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="https://protsenko.dev/spring-data-jpa-best-practices-repositories-design-guide/" rel="noopener noreferrer"&gt;Spring Data JPA Best Practices: Repositories Design Guide&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Some of the examples may seem obvious, but they’re not. It’s only from your experienced perspective. They’re real examples from the production code base.&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;Keep in mind that this series of articles explains the latest version of Spring Data JPA, so there may be nuances that I’ll highlight differently.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;h2&gt;
  
  
  Table of contents
&lt;/h2&gt;

&lt;ul&gt;
&lt;li&gt;
1&amp;nbsp;Manual and automatic transaction management

&lt;ul&gt;
&lt;li&gt;1.1 Using EntityManager to manage transactions&lt;/li&gt;
&lt;li&gt;1.2 Using TransactionTemplate&lt;/li&gt;
&lt;li&gt;1.3 Using @Transactional annotation&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;li&gt;
2. Manual Querying

&lt;ul&gt;
&lt;li&gt;2.1 Query vs TypedQuery&lt;/li&gt;
&lt;li&gt;2.2 Native Queries&lt;/li&gt;
&lt;li&gt;2.3 The Criteria API&lt;/li&gt;
&lt;li&gt;2.4 Passing parameters into queries&lt;/li&gt;
&lt;li&gt;2.5 Calling stored procedures&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;li&gt;
3&amp;nbsp;Projection data with EntityManager

&lt;ul&gt;
&lt;li&gt;3.1 Mapping entity to DTO with mapping libraries&lt;/li&gt;
&lt;li&gt;3.2 Mapping using a constructor&lt;/li&gt;
&lt;li&gt;3.3 Mapping with Tuple and Object Array&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;li&gt;At the end&lt;/li&gt;
&lt;/ul&gt;

&lt;h2&gt;
  
  
  1&amp;nbsp;Manual and automatic transaction management
&lt;/h2&gt;

&lt;p&gt;Imagine you need custom logic to work with your database, such as managing transactions, but &lt;a href="https://protsenko.dev/spring-data-jpa-best-practices-repositories-design-guide/" rel="noopener noreferrer"&gt;Spring Data JPA repositories&lt;/a&gt; are insufficient for you. So what could you do? Spring Data JPA offers various approaches to achieve this.&lt;/p&gt;

&lt;h3&gt;
  
  
  1.1 Using EntityManager to manage transactions
&lt;/h3&gt;

&lt;p&gt;You can use the JPA &lt;code&gt;EntityManager&lt;/code&gt; together with &lt;code&gt;EntityTransaction&lt;/code&gt; to manage transactions in Spring manually, as it provides low-level access to the persistence context and database operations, but managing transactions yourself quickly becomes error-prone and requires a lot of careful attention.&lt;/p&gt;

&lt;p&gt;There is one more catch: you cannot use the injected &lt;code&gt;EntityManager&lt;/code&gt; to start a transaction directly. In a typical Spring setup, that &lt;code&gt;EntityManager&lt;/code&gt; is a container-managed proxy, and Spring expects you to use its own transaction management mechanisms instead.&lt;/p&gt;

&lt;p&gt;Creating your own &lt;code&gt;EntityManager&lt;/code&gt; from an &lt;code&gt;EntityManagerFactory&lt;/code&gt; and using JPA’s &lt;code&gt;EntityTransaction&lt;/code&gt; API is technically possible, but it bypasses Spring’s transaction infrastructure and is generally discouraged except in very special cases.&lt;/p&gt;

&lt;p&gt;Let’s examine a small code example that utilizes the entity manager to manage transactions.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight java"&gt;&lt;code&gt;&lt;span class="k"&gt;try&lt;/span&gt; &lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="nc"&gt;EntityManager&lt;/span&gt; &lt;span class="n"&gt;em&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;emf&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;createEntityManager&lt;/span&gt;&lt;span class="o"&gt;())&lt;/span&gt; &lt;span class="o"&gt;{&lt;/span&gt;
    &lt;span class="nc"&gt;EntityTransaction&lt;/span&gt; &lt;span class="n"&gt;tx&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;em&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;getTransaction&lt;/span&gt;&lt;span class="o"&gt;();&lt;/span&gt;
    &lt;span class="k"&gt;try&lt;/span&gt; &lt;span class="o"&gt;{&lt;/span&gt;
        &lt;span class="n"&gt;tx&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;begin&lt;/span&gt;&lt;span class="o"&gt;();&lt;/span&gt;
        &lt;span class="n"&gt;em&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;persist&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="k"&gt;new&lt;/span&gt; &lt;span class="nc"&gt;MyEntity&lt;/span&gt;&lt;span class="o"&gt;());&lt;/span&gt;
        &lt;span class="n"&gt;tx&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;commit&lt;/span&gt;&lt;span class="o"&gt;();&lt;/span&gt;
    &lt;span class="o"&gt;}&lt;/span&gt; &lt;span class="k"&gt;catch&lt;/span&gt; &lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="nc"&gt;Exception&lt;/span&gt; &lt;span class="n"&gt;e&lt;/span&gt;&lt;span class="o"&gt;)&lt;/span&gt; &lt;span class="o"&gt;{&lt;/span&gt;
        &lt;span class="k"&gt;if&lt;/span&gt; &lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="n"&gt;tx&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;isActive&lt;/span&gt;&lt;span class="o"&gt;())&lt;/span&gt; &lt;span class="n"&gt;tx&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;rollback&lt;/span&gt;&lt;span class="o"&gt;();&lt;/span&gt;
        &lt;span class="k"&gt;throw&lt;/span&gt; &lt;span class="n"&gt;e&lt;/span&gt;&lt;span class="o"&gt;;&lt;/span&gt;
    &lt;span class="o"&gt;}&lt;/span&gt;
&lt;span class="o"&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Ouch! There is a lot of code. You should always use the entity manager factory to create an instance of the manager. Be careful, as it should be closed at the end of the logic. Additionally, ensure that commits and rollbacks are placed. That looks like a burden with different ways to shoot yourself in the foot.&lt;/p&gt;

&lt;p&gt;I couldn’t recommend this approach to managing transactions, but real life has plenty of nuances, and for some reason, you may have to use it. Actually, I used it before (spoiler: it was a legacy project), as I had complex low-level logic to manage database transactions.&lt;/p&gt;

&lt;h3&gt;
  
  
  &lt;strong&gt;1.2 Using TransactionTemplate&lt;/strong&gt;
&lt;/h3&gt;

&lt;p&gt;Manual transaction management with an entity manager is a headache, but Spring &lt;code&gt;@Transactional&lt;/code&gt; annotation too magical? There is a solution in the middle, it’s a &lt;code&gt;TransactionTemplate&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;This approach gives you the best of both worlds: you get programmatic control over exactly where a transaction starts and ends, but you let Spring handle commits, rollbacks, and closings of the entity manager.&lt;/p&gt;

&lt;p&gt;The beauty here is that, unlike the manual approach, you can use the injected &lt;code&gt;EntityManager&lt;/code&gt;. Because the transaction template interacts directly with Spring’s &lt;code&gt;PlatformTransactionManager&lt;/code&gt;, it correctly binds the transaction to the current thread, allowing the standard container-managed proxy to function exactly as intended.&lt;/p&gt;

&lt;p&gt;Look at this! The explicit &lt;code&gt;try-catch-finally&lt;/code&gt; block is gone, along with the closing entity manager.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight java"&gt;&lt;code&gt;&lt;span class="nd"&gt;@Service&lt;/span&gt;
&lt;span class="nd"&gt;@RequiredArgsConstructor&lt;/span&gt;
&lt;span class="kd"&gt;public&lt;/span&gt; &lt;span class="kd"&gt;class&lt;/span&gt; &lt;span class="nc"&gt;CustomTransactionService&lt;/span&gt; &lt;span class="o"&gt;{&lt;/span&gt;

    &lt;span class="kd"&gt;private&lt;/span&gt; &lt;span class="kd"&gt;final&lt;/span&gt; &lt;span class="nc"&gt;PlatformTransactionManager&lt;/span&gt; &lt;span class="n"&gt;txManager&lt;/span&gt;&lt;span class="o"&gt;;&lt;/span&gt;
    &lt;span class="kd"&gt;private&lt;/span&gt; &lt;span class="kd"&gt;final&lt;/span&gt; &lt;span class="nc"&gt;EntityManager&lt;/span&gt; &lt;span class="n"&gt;em&lt;/span&gt;&lt;span class="o"&gt;;&lt;/span&gt;

    &lt;span class="kd"&gt;public&lt;/span&gt; &lt;span class="kt"&gt;void&lt;/span&gt; &lt;span class="nf"&gt;saveSafely&lt;/span&gt;&lt;span class="o"&gt;()&lt;/span&gt; &lt;span class="o"&gt;{&lt;/span&gt;
        &lt;span class="nc"&gt;TransactionTemplate&lt;/span&gt; &lt;span class="n"&gt;tmplt&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="k"&gt;new&lt;/span&gt; &lt;span class="nc"&gt;TransactionTemplate&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="n"&gt;txManager&lt;/span&gt;&lt;span class="o"&gt;);&lt;/span&gt;

        &lt;span class="n"&gt;tmplt&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;executeWithoutResult&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="n"&gt;status&lt;/span&gt; &lt;span class="o"&gt;-&amp;gt;&lt;/span&gt; &lt;span class="o"&gt;{&lt;/span&gt;
            &lt;span class="n"&gt;em&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;persist&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="k"&gt;new&lt;/span&gt; &lt;span class="nc"&gt;MyEntity&lt;/span&gt;&lt;span class="o"&gt;());&lt;/span&gt; 
            &lt;span class="c1"&gt;// No manual commit needed; it happens automatically on exit.&lt;/span&gt;
        &lt;span class="o"&gt;});&lt;/span&gt;
    &lt;span class="o"&gt;}&lt;/span&gt;
&lt;span class="o"&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;If your code inside the lambda throws a &lt;code&gt;RuntimeException&lt;/code&gt;, the template automatically marks the transaction for rollback. If you need to roll it back based on a specific condition without throwing an exception, you can simply call &lt;code&gt;status.setRollbackOnly()&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;This is the preferred way to write “custom” transaction logic in the Spring ecosystem. It keeps your code clean, concise, and integrated with the container’s lifecycle.&lt;/p&gt;

&lt;h3&gt;
  
  
  1.3 Using @Transactional annotation
&lt;/h3&gt;

&lt;p&gt;Now we arrive at the most common approach. Why write code to manage transactions when you can just declare them with some Spring magic? This is the declarative style, and it is likely what I’ve seen in many Spring applications.&lt;/p&gt;

&lt;p&gt;Instead of injecting managers or creating templates, you simply annotate your method (or class) with &lt;code&gt;@Transactional&lt;/code&gt;. Spring’s AOP infrastructure takes over, wrapping your bean in a proxy that handles the &lt;code&gt;begin&lt;/code&gt;, &lt;code&gt;commit&lt;/code&gt;, and &lt;code&gt;rollback&lt;/code&gt; logic for you.&lt;/p&gt;

&lt;p&gt;It looks so simple, you focus entirely on business logic, and the container handles the atomicity.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight java"&gt;&lt;code&gt;&lt;span class="nd"&gt;@Service&lt;/span&gt;
&lt;span class="nd"&gt;@RequiredArgsConstructor&lt;/span&gt;
&lt;span class="kd"&gt;public&lt;/span&gt; &lt;span class="kd"&gt;class&lt;/span&gt; &lt;span class="nc"&gt;UserService&lt;/span&gt; &lt;span class="o"&gt;{&lt;/span&gt;

    &lt;span class="kd"&gt;private&lt;/span&gt; &lt;span class="kd"&gt;final&lt;/span&gt; &lt;span class="nc"&gt;UserRepository&lt;/span&gt; &lt;span class="n"&gt;userRepository&lt;/span&gt;&lt;span class="o"&gt;;&lt;/span&gt;

    &lt;span class="nd"&gt;@Transactional&lt;/span&gt;
    &lt;span class="kd"&gt;public&lt;/span&gt; &lt;span class="kt"&gt;void&lt;/span&gt; &lt;span class="nf"&gt;createUser&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="nc"&gt;String&lt;/span&gt; &lt;span class="n"&gt;name&lt;/span&gt;&lt;span class="o"&gt;)&lt;/span&gt; &lt;span class="o"&gt;{&lt;/span&gt;
        &lt;span class="n"&gt;userRepository&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;save&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="k"&gt;new&lt;/span&gt; &lt;span class="nc"&gt;User&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="n"&gt;name&lt;/span&gt;&lt;span class="o"&gt;));&lt;/span&gt;
        &lt;span class="c1"&gt;// If an unchecked exception (RuntimeException) is thrown here, &lt;/span&gt;
        &lt;span class="c1"&gt;// the transaction rolls back automatically.&lt;/span&gt;
    &lt;span class="o"&gt;}&lt;/span&gt;
&lt;span class="o"&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;However, there are many nuances. I’ll briefly explain some of them. However, the subject actually warrants a dedicated article.&lt;/p&gt;

&lt;p&gt;Since it relies on Spring proxies, the interception only happens when the method is called from outside the bean. If you call a transactional method from another method within the same class (self-invocation), the proxy is bypassed, and no transaction is started.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight java"&gt;&lt;code&gt;&lt;span class="nd"&gt;@Service&lt;/span&gt;
&lt;span class="kd"&gt;public&lt;/span&gt; &lt;span class="kd"&gt;class&lt;/span&gt; &lt;span class="nc"&gt;TicketService&lt;/span&gt; &lt;span class="o"&gt;{&lt;/span&gt;

    &lt;span class="c1"&gt;// 1. External caller invokes this method (Proxy intercepts here)&lt;/span&gt;
    &lt;span class="kd"&gt;public&lt;/span&gt; &lt;span class="kt"&gt;void&lt;/span&gt; &lt;span class="nf"&gt;bookBatch&lt;/span&gt;&lt;span class="o"&gt;()&lt;/span&gt; &lt;span class="o"&gt;{&lt;/span&gt;
        &lt;span class="c1"&gt;// 2. Inside the class, "this" refers to the raw Target object, not the Proxy.&lt;/span&gt;
        &lt;span class="c1"&gt;// 3. PROBLEM: Calling a @Transactional method from within the same class.&lt;/span&gt;
        &lt;span class="c1"&gt;// The Proxy is completely bypassed. No new transaction is started.&lt;/span&gt;
        &lt;span class="n"&gt;reserveSeat&lt;/span&gt;&lt;span class="o"&gt;();&lt;/span&gt; 
    &lt;span class="o"&gt;}&lt;/span&gt;

    &lt;span class="nd"&gt;@Transactional&lt;/span&gt;
    &lt;span class="kd"&gt;public&lt;/span&gt; &lt;span class="kt"&gt;void&lt;/span&gt; &lt;span class="nf"&gt;reserveSeat&lt;/span&gt;&lt;span class="o"&gt;()&lt;/span&gt; &lt;span class="o"&gt;{&lt;/span&gt;
        &lt;span class="c1"&gt;// Logic that EXPECTS a transaction, but won't get one &lt;/span&gt;
        &lt;span class="c1"&gt;// if called from bookBatch().&lt;/span&gt;
        &lt;span class="n"&gt;repo&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;save&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="k"&gt;new&lt;/span&gt; &lt;span class="nc"&gt;Ticket&lt;/span&gt;&lt;span class="o"&gt;());&lt;/span&gt;
    &lt;span class="o"&gt;}&lt;/span&gt;
&lt;span class="o"&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;In this scenario, if you call &lt;code&gt;bookBatch()&lt;/code&gt; from a Controller, Spring intercepts that first call, but when &lt;code&gt;bookBatch()&lt;/code&gt; calls &lt;code&gt;reserveSeat()&lt;/code&gt;, it is a direct Java method call inside the instance. Spring’s proxy wrapper is sitting outside, unaware that &lt;code&gt;reserveSeat()&lt;/code&gt; is running, so the spring transaction annotation is ignored.&lt;/p&gt;

&lt;p&gt;What else? Spring Proxies cannot intercept private methods. If you do so, Spring will silently ignore your annotation without errors or warnings, which could lead to significant problems and make your app unreliable. The best way to mark this annotation is for public methods only.&lt;/p&gt;

&lt;p&gt;One common bug in Spring transaction management is that transactions are always rolled back in the event of any exceptions. But it’s not, Spring only rolls back for &lt;code&gt;RuntimeException&lt;/code&gt; (unchecked) with its child and &lt;code&gt;Error&lt;/code&gt;. It does not rollback for checked exceptions (like &lt;code&gt;IOException&lt;/code&gt; or your custom &lt;code&gt;BusinessException&lt;/code&gt; if it extends from &lt;code&gt;Exception&lt;/code&gt;).&lt;/p&gt;

&lt;p&gt;Best practices here? Tell Spring what to rollback or extend your exceptions from &lt;code&gt;RuntimeException&lt;/code&gt; and you’ll sleep well.&lt;/p&gt;

&lt;p&gt;Using spring transactional annotation is a better approach than using an entity manager to manage transactions, as it eliminates the need for boilerplate code. However, you have to spend time learning all the nuances of using this annotation. Your education is a foundation for a better future for your applications.&lt;/p&gt;

&lt;h2&gt;
  
  
  2. Manual Querying
&lt;/h2&gt;

&lt;p&gt;Repositories are fantastic, and they could close 90% of your work. But for the last 10 percent, you’ve to write some queries in a less abstract way. For example, you need a complex report, a specific join, or a database-specific function that Spring Data’s method naming convention just can’t handle. You could use mentioned before &lt;code&gt;EntityManager&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;One important note: &lt;code&gt;EntityManager&lt;/code&gt; is a good way to query, but many tasks can be resolved with JPA repositories, as it provides a way to write native queries, and you don’t need to write boilerplate code as above. If your project has a convention for using an entity manager or other reasons, use it. Otherwise, give it a try to write queries with &lt;a href="https://protsenko.dev/spring-data-jpa-best-practices-repositories-design-guide/#h-2-nbsp-working-with-queries-in-repositories" rel="noopener noreferrer"&gt;Spring Data JPA repositories&lt;/a&gt;.&lt;/p&gt;

&lt;h3&gt;
  
  
  2.1 Query vs TypedQuery
&lt;/h3&gt;

&lt;p&gt;When you create a query in JPA, you have two choices. You can use the raw &lt;code&gt;Query&lt;/code&gt; interface, or the generic &lt;code&gt;TypedQuery&lt;/code&gt;. The raw &lt;code&gt;Query&lt;/code&gt; interface returns &lt;code&gt;Object&lt;/code&gt; or &lt;code&gt;List&amp;lt;?&amp;gt;&lt;/code&gt;. It tells the compiler, “Trust me, I know what I’m doing.” This forces you to manually cast the result, which is a code smell and a potential runtime crash waiting to happen.&lt;/p&gt;

&lt;p&gt;Just look at this example. There is casting data without verification, which could lead to different runtime problems; it’s better to avoid it.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight java"&gt;&lt;code&gt;&lt;span class="kd"&gt;public&lt;/span&gt; &lt;span class="nc"&gt;User&lt;/span&gt; &lt;span class="nf"&gt;getUserViaSimpleQuery&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="nc"&gt;Long&lt;/span&gt; &lt;span class="n"&gt;id&lt;/span&gt;&lt;span class="o"&gt;)&lt;/span&gt; &lt;span class="o"&gt;{&lt;/span&gt;
    &lt;span class="c1"&gt;// Returns a raw Query. We have to cast (User) manually.&lt;/span&gt;
    &lt;span class="nc"&gt;Query&lt;/span&gt; &lt;span class="n"&gt;query&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;entityManager&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;createQuery&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;
        &lt;span class="s"&gt;"SELECT u FROM User u WHERE u.id = :id"&lt;/span&gt;
    &lt;span class="o"&gt;);&lt;/span&gt;
    &lt;span class="n"&gt;query&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;setParameter&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="s"&gt;"id"&lt;/span&gt;&lt;span class="o"&gt;,&lt;/span&gt; &lt;span class="n"&gt;id&lt;/span&gt;&lt;span class="o"&gt;);&lt;/span&gt;
    &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="nc"&gt;User&lt;/span&gt;&lt;span class="o"&gt;)&lt;/span&gt; &lt;span class="n"&gt;query&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;getSingleResult&lt;/span&gt;&lt;span class="o"&gt;();&lt;/span&gt;
&lt;span class="o"&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Always prefer &lt;code&gt;TypedQuery&lt;/code&gt;. It carries the type information with it, allowing you to delete those unchecked casts and let the compiler help you.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight java"&gt;&lt;code&gt;&lt;span class="kd"&gt;public&lt;/span&gt; &lt;span class="nc"&gt;User&lt;/span&gt; &lt;span class="nf"&gt;getUserViaTypedQuery&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="nc"&gt;Long&lt;/span&gt; &lt;span class="n"&gt;id&lt;/span&gt;&lt;span class="o"&gt;)&lt;/span&gt; &lt;span class="o"&gt;{&lt;/span&gt;
    &lt;span class="c1"&gt;// Pass the class type! Now we get TypedQuery&amp;lt;User&amp;gt;&lt;/span&gt;
    &lt;span class="nc"&gt;TypedQuery&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="nc"&gt;User&lt;/span&gt;&lt;span class="o"&gt;&amp;gt;&lt;/span&gt; &lt;span class="n"&gt;query&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;entityManager&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;createQuery&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;
        &lt;span class="s"&gt;"SELECT u FROM User u WHERE u.id = :id"&lt;/span&gt;&lt;span class="o"&gt;,&lt;/span&gt; &lt;span class="nc"&gt;User&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;class&lt;/span&gt;
    &lt;span class="o"&gt;);&lt;/span&gt;
    &lt;span class="n"&gt;query&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;setParameter&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="s"&gt;"id"&lt;/span&gt;&lt;span class="o"&gt;,&lt;/span&gt; &lt;span class="n"&gt;id&lt;/span&gt;&lt;span class="o"&gt;);&lt;/span&gt;
    &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="n"&gt;query&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;getSingleResult&lt;/span&gt;&lt;span class="o"&gt;();&lt;/span&gt;
&lt;span class="o"&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h3&gt;
  
  
  2.2 Native Queries
&lt;/h3&gt;

&lt;p&gt;Sometimes JPQL isn’t enough. You need to use database-specific features (like &lt;code&gt;CONNECT BY&lt;/code&gt; in Oracle or specific window functions). This is a place where &lt;code&gt;createNativeQuery&lt;/code&gt; should be used. But there is a problem.&lt;/p&gt;

&lt;p&gt;If you are fetching a whole Entity, you can still map it. But if you are fetching a single column (scalar value), things get messy. In legacy code, I saw that developers were assuming that if a database column is a number, Java would return a &lt;code&gt;Long&lt;/code&gt;.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight java"&gt;&lt;code&gt;&lt;span class="kd"&gt;public&lt;/span&gt; &lt;span class="nc"&gt;Long&lt;/span&gt; &lt;span class="nf"&gt;getActiveVersionId&lt;/span&gt;&lt;span class="o"&gt;()&lt;/span&gt; &lt;span class="o"&gt;{&lt;/span&gt;
    &lt;span class="nc"&gt;Query&lt;/span&gt; &lt;span class="n"&gt;query&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;entityManager&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;createNativeQuery&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;
        &lt;span class="s"&gt;"select id from utl_rep_version_cfg where rownum = 1"&lt;/span&gt;
    &lt;span class="o"&gt;);&lt;/span&gt;
    &lt;span class="c1"&gt;// DANGER: In Oracle, this returns BigDecimal. &lt;/span&gt;
    &lt;span class="c1"&gt;// Casting (Long) throws ClassCastException!&lt;/span&gt;
    &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="nc"&gt;Long&lt;/span&gt;&lt;span class="o"&gt;)&lt;/span&gt; &lt;span class="n"&gt;query&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;getSingleResult&lt;/span&gt;&lt;span class="o"&gt;();&lt;/span&gt; 
&lt;span class="o"&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;If you run this against Oracle, your app will throw exceptions. The JDBC driver often maps numbers to &lt;code&gt;BigDecimal&lt;/code&gt; or &lt;code&gt;BigInteger&lt;/code&gt;, and you cannot cast an object of type &lt;code&gt;BigDecimal&lt;/code&gt; directly to &lt;code&gt;Long&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;When dealing with native queries and scalars, treat the result as a generic &lt;code&gt;Number&lt;/code&gt;. It may seem verbose, but this approach is safer than the previous one. Use it or not; it’s only your choice. However, I suggest learning a bit about JDBC data mapping, especially for your DBMS. For Oracle, you can refer to this &lt;a href="https://docs.oracle.com/cd/E11882_01/java.112/e10587/datamap.htm#JJPUB24092" rel="noopener noreferrer"&gt;documentation&lt;/a&gt;.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight java"&gt;&lt;code&gt;&lt;span class="kd"&gt;public&lt;/span&gt; &lt;span class="nc"&gt;Long&lt;/span&gt; &lt;span class="nf"&gt;getActiveVersionId&lt;/span&gt;&lt;span class="o"&gt;()&lt;/span&gt; &lt;span class="o"&gt;{&lt;/span&gt;
    &lt;span class="nc"&gt;Query&lt;/span&gt; &lt;span class="n"&gt;query&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;entityManager&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;createNativeQuery&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;
        &lt;span class="s"&gt;"select id from utl_rep_version_cfg where rownum = 1"&lt;/span&gt;
    &lt;span class="o"&gt;);&lt;/span&gt;
    &lt;span class="nc"&gt;Object&lt;/span&gt; &lt;span class="n"&gt;result&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;query&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;getSingleResult&lt;/span&gt;&lt;span class="o"&gt;();&lt;/span&gt;
    &lt;span class="c1"&gt;// Safely convert whatever number the DB driver returns&lt;/span&gt;
    &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="n"&gt;result&lt;/span&gt; &lt;span class="o"&gt;!=&lt;/span&gt; &lt;span class="kc"&gt;null&lt;/span&gt; &lt;span class="o"&gt;?&lt;/span&gt; &lt;span class="o"&gt;((&lt;/span&gt;&lt;span class="nc"&gt;Number&lt;/span&gt;&lt;span class="o"&gt;)&lt;/span&gt; &lt;span class="n"&gt;result&lt;/span&gt;&lt;span class="o"&gt;).&lt;/span&gt;&lt;span class="na"&gt;longValue&lt;/span&gt;&lt;span class="o"&gt;()&lt;/span&gt; &lt;span class="o"&gt;:&lt;/span&gt; &lt;span class="kc"&gt;null&lt;/span&gt;&lt;span class="o"&gt;;&lt;/span&gt;
&lt;span class="o"&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h3&gt;
  
  
  2.3 The Criteria API
&lt;/h3&gt;

&lt;p&gt;If &lt;code&gt;TypedQuery&lt;/code&gt; is safe, the Criteria API adds more type safety. It allows you to build queries programmatically, protecting you from typical problems. However, I must admit that I dislike the criteria code because it is overly wordy. It’s hard to read. It looks like you are writing an abstract syntax tree instead of SQL. However, it is the only safe way to build dynamic queries where filters change at runtime.&lt;/p&gt;

&lt;p&gt;Unfortunately, I have seen this a lot. One of the common security bugs is passing parameters with string concatenation. This approach leads to problems because user input is not sanitized properly and becomes part of the raw SQL query. To solve this, you could use named parameters and pass them safely, or you could also utilize the criteria API for this purpose.&lt;/p&gt;

&lt;p&gt;The following example is not complex and highlights only the SQL injection issue. In the real world, developers often use a criteria API to build custom filters depending on user input.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight java"&gt;&lt;code&gt;&lt;span class="c1"&gt;// BAD: Concatenation logic that creates a wide-open security hole&lt;/span&gt;
&lt;span class="kd"&gt;public&lt;/span&gt; &lt;span class="kt"&gt;boolean&lt;/span&gt; &lt;span class="nf"&gt;login&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="nc"&gt;String&lt;/span&gt; &lt;span class="n"&gt;username&lt;/span&gt;&lt;span class="o"&gt;,&lt;/span&gt; &lt;span class="nc"&gt;String&lt;/span&gt; &lt;span class="n"&gt;password&lt;/span&gt;&lt;span class="o"&gt;)&lt;/span&gt; &lt;span class="o"&gt;{&lt;/span&gt;

    &lt;span class="c1"&gt;// DANGER: We are pasting user input directly into the query string.&lt;/span&gt;
    &lt;span class="nc"&gt;String&lt;/span&gt; &lt;span class="n"&gt;hql&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="s"&gt;"SELECT count(u) FROM User u "&lt;/span&gt; &lt;span class="o"&gt;+&lt;/span&gt; 
                 &lt;span class="s"&gt;"WHERE u.username = '"&lt;/span&gt; &lt;span class="o"&gt;+&lt;/span&gt; &lt;span class="n"&gt;username&lt;/span&gt; &lt;span class="o"&gt;+&lt;/span&gt; &lt;span class="s"&gt;"'"&lt;/span&gt; &lt;span class="o"&gt;+&lt;/span&gt; 
                 &lt;span class="s"&gt;"AND u.password = '"&lt;/span&gt; &lt;span class="o"&gt;+&lt;/span&gt; &lt;span class="n"&gt;password&lt;/span&gt; &lt;span class="o"&gt;+&lt;/span&gt; &lt;span class="s"&gt;"'"&lt;/span&gt;&lt;span class="o"&gt;;&lt;/span&gt;

    &lt;span class="nc"&gt;Long&lt;/span&gt; &lt;span class="n"&gt;count&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="nc"&gt;Long&lt;/span&gt;&lt;span class="o"&gt;)&lt;/span&gt; &lt;span class="n"&gt;entityManager&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;createQuery&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="n"&gt;hql&lt;/span&gt;&lt;span class="o"&gt;).&lt;/span&gt;&lt;span class="na"&gt;getSingleResult&lt;/span&gt;&lt;span class="o"&gt;();&lt;/span&gt;
    &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="n"&gt;count&lt;/span&gt; &lt;span class="o"&gt;&amp;gt;&lt;/span&gt; &lt;span class="mi"&gt;0&lt;/span&gt;&lt;span class="o"&gt;;&lt;/span&gt;
&lt;span class="o"&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Let’s take a look at the alternative criteria: Yes, this is a lot of code, but we’ve introduced simple logic. If the password is missing, it shouldn’t be used in the WHERE clause. When using simple queries, string concatenation is required, which can lead to security issues. Here, you’re avoiding this, bringing more flexibility, but overall, it adds complexity to your codebase.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight java"&gt;&lt;code&gt;&lt;span class="kd"&gt;public&lt;/span&gt; &lt;span class="kt"&gt;boolean&lt;/span&gt; &lt;span class="nf"&gt;loginSafe&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="nc"&gt;String&lt;/span&gt; &lt;span class="n"&gt;username&lt;/span&gt;&lt;span class="o"&gt;,&lt;/span&gt; &lt;span class="nc"&gt;String&lt;/span&gt; &lt;span class="n"&gt;password&lt;/span&gt;&lt;span class="o"&gt;)&lt;/span&gt; &lt;span class="o"&gt;{&lt;/span&gt;
    &lt;span class="nc"&gt;CriteriaBuilder&lt;/span&gt; &lt;span class="n"&gt;cb&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;entityManager&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;getCriteriaBuilder&lt;/span&gt;&lt;span class="o"&gt;();&lt;/span&gt;
    &lt;span class="nc"&gt;CriteriaQuery&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="nc"&gt;Long&lt;/span&gt;&lt;span class="o"&gt;&amp;gt;&lt;/span&gt; &lt;span class="n"&gt;cq&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;cb&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;createQuery&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="nc"&gt;Long&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;class&lt;/span&gt;&lt;span class="o"&gt;);&lt;/span&gt;
    &lt;span class="nc"&gt;Root&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="nc"&gt;User&lt;/span&gt;&lt;span class="o"&gt;&amp;gt;&lt;/span&gt; &lt;span class="n"&gt;user&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;cq&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;from&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="nc"&gt;User&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;class&lt;/span&gt;&lt;span class="o"&gt;);&lt;/span&gt;

    &lt;span class="c1"&gt;// 1. We want to count users&lt;/span&gt;
    &lt;span class="n"&gt;cq&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;select&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="n"&gt;cb&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;count&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="n"&gt;user&lt;/span&gt;&lt;span class="o"&gt;));&lt;/span&gt;

    &lt;span class="c1"&gt;// 2. Build predicates dynamically&lt;/span&gt;
    &lt;span class="nc"&gt;List&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="nc"&gt;Predicate&lt;/span&gt;&lt;span class="o"&gt;&amp;gt;&lt;/span&gt; &lt;span class="n"&gt;predicates&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="k"&gt;new&lt;/span&gt; &lt;span class="nc"&gt;ArrayList&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&amp;gt;();&lt;/span&gt;
    &lt;span class="n"&gt;predicates&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;add&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="n"&gt;cb&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;equal&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="n"&gt;user&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;get&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="s"&gt;"username"&lt;/span&gt;&lt;span class="o"&gt;),&lt;/span&gt; &lt;span class="n"&gt;username&lt;/span&gt;&lt;span class="o"&gt;));&lt;/span&gt;

    &lt;span class="c1"&gt;// Example of dynamic logic: simple IF statement, no string mess&lt;/span&gt;
    &lt;span class="k"&gt;if&lt;/span&gt; &lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="n"&gt;password&lt;/span&gt; &lt;span class="o"&gt;!=&lt;/span&gt; &lt;span class="kc"&gt;null&lt;/span&gt;&lt;span class="o"&gt;)&lt;/span&gt; &lt;span class="o"&gt;{&lt;/span&gt;
        &lt;span class="n"&gt;predicates&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;add&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="n"&gt;cb&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;equal&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="n"&gt;user&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;get&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="s"&gt;"password"&lt;/span&gt;&lt;span class="o"&gt;),&lt;/span&gt; &lt;span class="n"&gt;password&lt;/span&gt;&lt;span class="o"&gt;));&lt;/span&gt;
    &lt;span class="o"&gt;}&lt;/span&gt;

    &lt;span class="n"&gt;cq&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;where&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="n"&gt;predicates&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;toArray&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="k"&gt;new&lt;/span&gt; &lt;span class="nc"&gt;Predicate&lt;/span&gt;&lt;span class="o"&gt;[&lt;/span&gt;&lt;span class="mi"&gt;0&lt;/span&gt;&lt;span class="o"&gt;]));&lt;/span&gt;

    &lt;span class="c1"&gt;// 3. Execute safely&lt;/span&gt;
    &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="n"&gt;entityManager&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;createQuery&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="n"&gt;cq&lt;/span&gt;&lt;span class="o"&gt;).&lt;/span&gt;&lt;span class="na"&gt;getSingleResult&lt;/span&gt;&lt;span class="o"&gt;()&lt;/span&gt; &lt;span class="o"&gt;&amp;gt;&lt;/span&gt; &lt;span class="mi"&gt;0&lt;/span&gt;&lt;span class="o"&gt;;&lt;/span&gt;
&lt;span class="o"&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;As I mentioned earlier, I don’t like this approach because it’s too wordy, contains a lot of code, and adds complexity. However, on the other hand, you could use string concatenation. It’s not pure evil. With a proper approach, there wouldn’t be a problem, but it’s a slippery road you’ve to avoid.&lt;/p&gt;

&lt;h3&gt;
  
  
  2.4 Passing parameters into queries
&lt;/h3&gt;

&lt;p&gt;We have discussed how to write the queries, and in the example code, I used named parameters to pass parameters safely. This may seem trivial, but in a large codebase, differences in passing parameters can cause significant issues. There are generally two ways to pass parameters: positional (?) and named (:id). If you value your sanity and the time of your colleagues, you should have a strong preference for this approach. For me, it’s named parameters.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Positional parameters&lt;/strong&gt; are a relic. They depend entirely on the order of arguments. If a developer comes along six months later and adds a new condition in the middle of your &lt;code&gt;WHERE&lt;/code&gt; clause, the parameter indexes shift, and your code breaks – often silently or with confusing data errors.&lt;/p&gt;

&lt;p&gt;Look at this fragile code. You need to mentally prepare to update and verify the passed parameters and their indexes. To me, it’s not as cool as it seems, as it leads to problems. If you could avoid problems from the start, it’s better to avoid them.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight java"&gt;&lt;code&gt;&lt;span class="nc"&gt;TypedQuery&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="nc"&gt;User&lt;/span&gt;&lt;span class="o"&gt;&amp;gt;&lt;/span&gt; &lt;span class="n"&gt;q&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;em&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;createQuery&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;
    &lt;span class="s"&gt;"SELECT u FROM User u WHERE u.id = ?1 AND u.status = ?2"&lt;/span&gt;&lt;span class="o"&gt;,&lt;/span&gt;
    &lt;span class="nc"&gt;User&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;class&lt;/span&gt;
&lt;span class="o"&gt;);&lt;/span&gt;

&lt;span class="n"&gt;q&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;setParameter&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;1&lt;/span&gt;&lt;span class="o"&gt;,&lt;/span&gt; &lt;span class="n"&gt;id&lt;/span&gt;&lt;span class="o"&gt;);&lt;/span&gt;
&lt;span class="n"&gt;q&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;setParameter&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;2&lt;/span&gt;&lt;span class="o"&gt;,&lt;/span&gt; &lt;span class="nc"&gt;Status&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;ACTIVE&lt;/span&gt;&lt;span class="o"&gt;);&lt;/span&gt;

&lt;span class="c1"&gt;//and with native query&lt;/span&gt;
&lt;span class="nc"&gt;Query&lt;/span&gt; &lt;span class="n"&gt;q&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;em&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;createNativeQuery&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;
    &lt;span class="s"&gt;"SELECT * FROM users WHERE id = ? AND status = ?"&lt;/span&gt;&lt;span class="o"&gt;,&lt;/span&gt;
    &lt;span class="nc"&gt;User&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;class&lt;/span&gt;
&lt;span class="o"&gt;);&lt;/span&gt;
&lt;span class="n"&gt;q&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;setParameter&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;1&lt;/span&gt;&lt;span class="o"&gt;,&lt;/span&gt; &lt;span class="n"&gt;id&lt;/span&gt;&lt;span class="o"&gt;);&lt;/span&gt;
&lt;span class="n"&gt;q&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;setParameter&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;2&lt;/span&gt;&lt;span class="o"&gt;,&lt;/span&gt; &lt;span class="s"&gt;"ACTIVE"&lt;/span&gt;&lt;span class="o"&gt;);&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;After seeing this example, I hope you find named parameters more effective, as they provide a clearer way to keep your code clean and maintainable. Just look at this example. This is kind of self-documented code. The parameter names tell us what they are, and we don’t need to concern ourselves with indexes for now.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight java"&gt;&lt;code&gt;&lt;span class="nc"&gt;TypedQuery&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="nc"&gt;User&lt;/span&gt;&lt;span class="o"&gt;&amp;gt;&lt;/span&gt; &lt;span class="n"&gt;q&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;em&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;createQuery&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;
    &lt;span class="s"&gt;"SELECT u FROM User u WHERE u.id = :id AND u.status = :status"&lt;/span&gt;&lt;span class="o"&gt;,&lt;/span&gt;
    &lt;span class="nc"&gt;User&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;class&lt;/span&gt;
&lt;span class="o"&gt;);&lt;/span&gt;

&lt;span class="n"&gt;q&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;setParameter&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="s"&gt;"id"&lt;/span&gt;&lt;span class="o"&gt;,&lt;/span&gt; &lt;span class="n"&gt;id&lt;/span&gt;&lt;span class="o"&gt;);&lt;/span&gt;
&lt;span class="n"&gt;q&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;setParameter&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="s"&gt;"status"&lt;/span&gt;&lt;span class="o"&gt;,&lt;/span&gt; &lt;span class="nc"&gt;Status&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;ACTIVE&lt;/span&gt;&lt;span class="o"&gt;);&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h3&gt;
  
  
  2.5 Calling stored procedures
&lt;/h3&gt;

&lt;p&gt;You can also call stored procedures via the &lt;code&gt;EntityManager&lt;/code&gt;.&lt;br&gt;&lt;br&gt;
The usual pattern is:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;Create a &lt;code&gt;StoredProcedureQuery&lt;/code&gt; by specifying the procedure name&lt;/li&gt;
&lt;li&gt;Register all parameters with &lt;code&gt;registerStoredProcedureParameter&lt;/code&gt;
&lt;/li&gt;
&lt;li&gt;Set the parameter values&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;In many codebases, these last two steps differ – registering a parameter, setting it, and then registering the next one. This makes the code jump back and forth between two ideas (declaring parameters and providing values). I find it clearer to first register all parameters and only then set their values, but this is mostly a matter of preference.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight java"&gt;&lt;code&gt;&lt;span class="kd"&gt;public&lt;/span&gt; &lt;span class="kt"&gt;void&lt;/span&gt; &lt;span class="nf"&gt;execute&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="nc"&gt;Long&lt;/span&gt; &lt;span class="n"&gt;userId&lt;/span&gt;&lt;span class="o"&gt;)&lt;/span&gt; &lt;span class="o"&gt;{&lt;/span&gt;
    &lt;span class="nc"&gt;StoredProcedureQuery&lt;/span&gt; &lt;span class="n"&gt;spq&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt;
        &lt;span class="n"&gt;em&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;createStoredProcedureQuery&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="s"&gt;"pkg_base_computing.recalc"&lt;/span&gt;&lt;span class="o"&gt;);&lt;/span&gt;

    &lt;span class="n"&gt;spq&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;registerStoredProcedureParameter&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="s"&gt;"p_user_id"&lt;/span&gt;&lt;span class="o"&gt;,&lt;/span&gt;   &lt;span class="nc"&gt;Long&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;class&lt;/span&gt;&lt;span class="o"&gt;,&lt;/span&gt; &lt;span class="nc"&gt;ParameterMode&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;IN&lt;/span&gt;&lt;span class="o"&gt;);&lt;/span&gt;
    &lt;span class="n"&gt;spq&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;setParameter&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="s"&gt;"p_user_id"&lt;/span&gt;&lt;span class="o"&gt;,&lt;/span&gt; &lt;span class="n"&gt;userId&lt;/span&gt;&lt;span class="o"&gt;);&lt;/span&gt;

    &lt;span class="n"&gt;spq&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;registerStoredProcedureParameter&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="s"&gt;"p_result_id"&lt;/span&gt;&lt;span class="o"&gt;,&lt;/span&gt; &lt;span class="nc"&gt;Long&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;class&lt;/span&gt;&lt;span class="o"&gt;,&lt;/span&gt; &lt;span class="nc"&gt;ParameterMode&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;OUT&lt;/span&gt;&lt;span class="o"&gt;);&lt;/span&gt;

    &lt;span class="n"&gt;spq&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;execute&lt;/span&gt;&lt;span class="o"&gt;();&lt;/span&gt;
&lt;span class="o"&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;For better readability, first register all parameters and then assign their values.&lt;br&gt;&lt;br&gt;
It’s a small stylistic change, but it slightly improves readability and maintainability, because with a quick glance, you can see which parameters the procedure uses.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight java"&gt;&lt;code&gt;&lt;span class="kd"&gt;public&lt;/span&gt; &lt;span class="kt"&gt;void&lt;/span&gt; &lt;span class="nf"&gt;execute&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="nc"&gt;Long&lt;/span&gt; &lt;span class="n"&gt;userId&lt;/span&gt;&lt;span class="o"&gt;)&lt;/span&gt; &lt;span class="o"&gt;{&lt;/span&gt;
    &lt;span class="nc"&gt;StoredProcedureQuery&lt;/span&gt; &lt;span class="n"&gt;spq&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt;
            &lt;span class="n"&gt;em&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;createStoredProcedureQuery&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="s"&gt;"pkg_base_computing.recalc"&lt;/span&gt;&lt;span class="o"&gt;);&lt;/span&gt;

    &lt;span class="n"&gt;spq&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;registerStoredProcedureParameter&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="s"&gt;"p_user_id"&lt;/span&gt;&lt;span class="o"&gt;,&lt;/span&gt;   &lt;span class="nc"&gt;Long&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;class&lt;/span&gt;&lt;span class="o"&gt;,&lt;/span&gt; &lt;span class="nc"&gt;ParameterMode&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;IN&lt;/span&gt;&lt;span class="o"&gt;);&lt;/span&gt;
    &lt;span class="n"&gt;spq&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;registerStoredProcedureParameter&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="s"&gt;"p_result_id"&lt;/span&gt;&lt;span class="o"&gt;,&lt;/span&gt; &lt;span class="nc"&gt;Long&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;class&lt;/span&gt;&lt;span class="o"&gt;,&lt;/span&gt; &lt;span class="nc"&gt;ParameterMode&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;OUT&lt;/span&gt;&lt;span class="o"&gt;);&lt;/span&gt;

    &lt;span class="n"&gt;spq&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;setParameter&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="s"&gt;"p_user_id"&lt;/span&gt;&lt;span class="o"&gt;,&lt;/span&gt; &lt;span class="n"&gt;userId&lt;/span&gt;&lt;span class="o"&gt;);&lt;/span&gt;

    &lt;span class="n"&gt;spq&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;execute&lt;/span&gt;&lt;span class="o"&gt;();&lt;/span&gt;
&lt;span class="o"&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  3&amp;nbsp;Projection data with EntityManager
&lt;/h2&gt;

&lt;p&gt;In the previous article about &lt;a href="https://protsenko.dev/spring-data-jpa-best-practices-repositories-design-guide/#h-3-nbsp-spring-data-jpa-projections" rel="noopener noreferrer"&gt;Spring Data JPA repositories&lt;/a&gt;, we discussed how to project data into DTOs or Interfaces. However, when using &lt;code&gt;EntityManager&lt;/code&gt;, you must handle projections manually. You generally have three options: mapping an entity after fetching it, selecting directly into a DTO, or dealing with raw data.&lt;/p&gt;

&lt;h3&gt;
  
  
  3.1 Mapping entity to DTO with mapping libraries
&lt;/h3&gt;

&lt;p&gt;The easiest way to get a DTO is to fetch the Entity and map it. Libraries like MapStruct or ModelMapper make your code cleaner and more readable (probably).&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight java"&gt;&lt;code&gt;&lt;span class="kd"&gt;public&lt;/span&gt; &lt;span class="nc"&gt;UserDto&lt;/span&gt; &lt;span class="nf"&gt;getUserDtoViaMap&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="nc"&gt;Long&lt;/span&gt; &lt;span class="n"&gt;id&lt;/span&gt;&lt;span class="o"&gt;)&lt;/span&gt; &lt;span class="o"&gt;{&lt;/span&gt;
    &lt;span class="c1"&gt;// 1. Fetches the WHOLE entity (all columns)&lt;/span&gt;
    &lt;span class="nc"&gt;User&lt;/span&gt; &lt;span class="n"&gt;user&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;entityManager&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;find&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="nc"&gt;User&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;class&lt;/span&gt;&lt;span class="o"&gt;,&lt;/span&gt; &lt;span class="n"&gt;id&lt;/span&gt;&lt;span class="o"&gt;);&lt;/span&gt;

    &lt;span class="c1"&gt;// 2. Maps it in memory&lt;/span&gt;
    &lt;span class="nc"&gt;UserDto&lt;/span&gt; &lt;span class="n"&gt;userDto&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="k"&gt;new&lt;/span&gt; &lt;span class="nc"&gt;UserDto&lt;/span&gt;&lt;span class="o"&gt;();&lt;/span&gt;
    &lt;span class="n"&gt;modelMapper&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;map&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="n"&gt;user&lt;/span&gt;&lt;span class="o"&gt;,&lt;/span&gt; &lt;span class="n"&gt;userDto&lt;/span&gt;&lt;span class="o"&gt;);&lt;/span&gt;
    &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="n"&gt;userDto&lt;/span&gt;&lt;span class="o"&gt;;&lt;/span&gt;
&lt;span class="o"&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;This is functionally correct. Mapping libraries use some magic to generate the mapping logic, and while they might introduce a tiny bit of CPU overhead (especially reflection-based ones like ModelMapper), they generally make your work easier.&lt;/p&gt;

&lt;h3&gt;
  
  
  3.2 Mapping using a constructor
&lt;/h3&gt;

&lt;p&gt;If you use JPQL, you can construct the DTO directly inside the query. This query is faster because the database only sends the columns you asked for. However, there is one major problem: you must specify the full path to the DTO.&lt;/p&gt;

&lt;p&gt;Why is this a problem? If you rename your DTO class or move it to a different package, the string in your query won’t update automatically. The compiler misses this problem, and it will only appear as a &lt;code&gt;RuntimeException&lt;/code&gt; when the code is executed. IntelliJ IDEA is smart enough to catch this and highlight it, but only if you analyze your entire codebase or open the specific file. If you miss the IDE warning, you are shipping a bug.&lt;/p&gt;

&lt;p&gt;Here is a small example of using constructor expressions:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight java"&gt;&lt;code&gt;&lt;span class="kd"&gt;public&lt;/span&gt; &lt;span class="nc"&gt;UserDto&lt;/span&gt; &lt;span class="nf"&gt;getUserDtoViaQuery&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="nc"&gt;Long&lt;/span&gt; &lt;span class="n"&gt;id&lt;/span&gt;&lt;span class="o"&gt;)&lt;/span&gt; &lt;span class="o"&gt;{&lt;/span&gt;
    &lt;span class="c1"&gt;// Note: You must use the fully qualified class name!&lt;/span&gt;
    &lt;span class="nc"&gt;TypedQuery&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="nc"&gt;UserDto&lt;/span&gt;&lt;span class="o"&gt;&amp;gt;&lt;/span&gt; &lt;span class="n"&gt;query&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;entityManager&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;createQuery&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;
        &lt;span class="s"&gt;"SELECT new com.app.dto.UserDto(u.username, u.email) "&lt;/span&gt; &lt;span class="o"&gt;+&lt;/span&gt;
        &lt;span class="s"&gt;"FROM User u WHERE u.id = :id"&lt;/span&gt;&lt;span class="o"&gt;,&lt;/span&gt;
        &lt;span class="nc"&gt;UserDto&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;class&lt;/span&gt;
    &lt;span class="o"&gt;);&lt;/span&gt;
    &lt;span class="n"&gt;query&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;setParameter&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="s"&gt;"id"&lt;/span&gt;&lt;span class="o"&gt;,&lt;/span&gt; &lt;span class="n"&gt;id&lt;/span&gt;&lt;span class="o"&gt;);&lt;/span&gt;
    &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="n"&gt;query&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;getSingleResult&lt;/span&gt;&lt;span class="o"&gt;();&lt;/span&gt;
&lt;span class="o"&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h3&gt;
  
  
  3.3 Mapping with Tuple and Object Array
&lt;/h3&gt;

&lt;p&gt;When you are forced to use Native SQL, you can’t use the &lt;code&gt;new Class(...)&lt;/code&gt; syntax. This leaves you with a choice: the raw Object array or strictly typed Tuples.&lt;/p&gt;

&lt;p&gt;Actually, it’s insane, it’s scary as hell, but I see this often. Let me introduce – using object arrays for data mapping. You get an array of generic objects, and you have to know which index corresponds to which column and what type it is. If something changes in the database or you modify the indexes, an exception occurs.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight java"&gt;&lt;code&gt;&lt;span class="c1"&gt;// BAD: Object[] projection (Hard to read, error-prone)&lt;/span&gt;
&lt;span class="kd"&gt;public&lt;/span&gt; &lt;span class="nc"&gt;List&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="nc"&gt;UserDto&lt;/span&gt;&lt;span class="o"&gt;&amp;gt;&lt;/span&gt; &lt;span class="nf"&gt;getActiveUsersBad&lt;/span&gt;&lt;span class="o"&gt;()&lt;/span&gt; &lt;span class="o"&gt;{&lt;/span&gt;
    &lt;span class="nc"&gt;List&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="nc"&gt;Object&lt;/span&gt;&lt;span class="o"&gt;[]&amp;gt;&lt;/span&gt; &lt;span class="n"&gt;results&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;entityManager&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;createNativeQuery&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;
        &lt;span class="s"&gt;"SELECT id, username, is_active FROM users WHERE is_active = 1"&lt;/span&gt;
    &lt;span class="o"&gt;).&lt;/span&gt;&lt;span class="na"&gt;getResultList&lt;/span&gt;&lt;span class="o"&gt;();&lt;/span&gt;

    &lt;span class="nc"&gt;List&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="nc"&gt;UserDto&lt;/span&gt;&lt;span class="o"&gt;&amp;gt;&lt;/span&gt; &lt;span class="n"&gt;dtos&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="k"&gt;new&lt;/span&gt; &lt;span class="nc"&gt;ArrayList&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&amp;gt;();&lt;/span&gt;

    &lt;span class="k"&gt;for&lt;/span&gt; &lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="nc"&gt;Object&lt;/span&gt;&lt;span class="o"&gt;[]&lt;/span&gt; &lt;span class="n"&gt;row&lt;/span&gt; &lt;span class="o"&gt;:&lt;/span&gt; &lt;span class="n"&gt;results&lt;/span&gt;&lt;span class="o"&gt;)&lt;/span&gt; &lt;span class="o"&gt;{&lt;/span&gt;
        &lt;span class="c1"&gt;// MAGIC NUMBERS! What is row[1]? What is row[2]?&lt;/span&gt;
        &lt;span class="c1"&gt;// You have to manually cast everything.&lt;/span&gt;
        &lt;span class="nc"&gt;Long&lt;/span&gt; &lt;span class="n"&gt;id&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;row&lt;/span&gt;&lt;span class="o"&gt;[&lt;/span&gt;&lt;span class="mi"&gt;0&lt;/span&gt;&lt;span class="o"&gt;]&lt;/span&gt; &lt;span class="o"&gt;!=&lt;/span&gt; &lt;span class="kc"&gt;null&lt;/span&gt; &lt;span class="o"&gt;?&lt;/span&gt; &lt;span class="o"&gt;((&lt;/span&gt;&lt;span class="nc"&gt;Number&lt;/span&gt;&lt;span class="o"&gt;)&lt;/span&gt; &lt;span class="n"&gt;row&lt;/span&gt;&lt;span class="o"&gt;[&lt;/span&gt;&lt;span class="mi"&gt;0&lt;/span&gt;&lt;span class="o"&gt;]).&lt;/span&gt;&lt;span class="na"&gt;longValue&lt;/span&gt;&lt;span class="o"&gt;()&lt;/span&gt; &lt;span class="o"&gt;:&lt;/span&gt; &lt;span class="kc"&gt;null&lt;/span&gt;&lt;span class="o"&gt;;&lt;/span&gt;
        &lt;span class="nc"&gt;String&lt;/span&gt; &lt;span class="n"&gt;username&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="nc"&gt;String&lt;/span&gt;&lt;span class="o"&gt;)&lt;/span&gt; &lt;span class="n"&gt;row&lt;/span&gt;&lt;span class="o"&gt;[&lt;/span&gt;&lt;span class="mi"&gt;1&lt;/span&gt;&lt;span class="o"&gt;];&lt;/span&gt;
        &lt;span class="nc"&gt;Boolean&lt;/span&gt; &lt;span class="n"&gt;active&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="nc"&gt;Boolean&lt;/span&gt;&lt;span class="o"&gt;)&lt;/span&gt; &lt;span class="n"&gt;row&lt;/span&gt;&lt;span class="o"&gt;[&lt;/span&gt;&lt;span class="mi"&gt;2&lt;/span&gt;&lt;span class="o"&gt;];&lt;/span&gt; &lt;span class="c1"&gt;// Hope this isn't a BigDecimal in Oracle!&lt;/span&gt;

        &lt;span class="n"&gt;dtos&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;add&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="k"&gt;new&lt;/span&gt; &lt;span class="nc"&gt;UserDto&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="n"&gt;id&lt;/span&gt;&lt;span class="o"&gt;,&lt;/span&gt; &lt;span class="n"&gt;username&lt;/span&gt;&lt;span class="o"&gt;,&lt;/span&gt; &lt;span class="n"&gt;active&lt;/span&gt;&lt;span class="o"&gt;));&lt;/span&gt;
    &lt;span class="o"&gt;}&lt;/span&gt;
    &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="n"&gt;dtos&lt;/span&gt;&lt;span class="o"&gt;;&lt;/span&gt;
&lt;span class="o"&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The better way is to use &lt;code&gt;Tuple&lt;/code&gt; interface. It allows you to access results by alias (name) rather than index. It is cleaner, safer, and self-documenting.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight java"&gt;&lt;code&gt;&lt;span class="c1"&gt;// BETTER: Tuple projection with aliases&lt;/span&gt;
&lt;span class="kd"&gt;public&lt;/span&gt; &lt;span class="nc"&gt;List&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="nc"&gt;UserDto&lt;/span&gt;&lt;span class="o"&gt;&amp;gt;&lt;/span&gt; &lt;span class="nf"&gt;getActiveUsersSafe&lt;/span&gt;&lt;span class="o"&gt;()&lt;/span&gt; &lt;span class="o"&gt;{&lt;/span&gt;
    &lt;span class="c1"&gt;// 1. Note the aliases (AS id, AS username)&lt;/span&gt;
    &lt;span class="nc"&gt;List&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="nc"&gt;Tuple&lt;/span&gt;&lt;span class="o"&gt;&amp;gt;&lt;/span&gt; &lt;span class="n"&gt;tuples&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;entityManager&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;createNativeQuery&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;
        &lt;span class="s"&gt;"SELECT u.id AS id, u.username AS username, u.is_active AS active "&lt;/span&gt; &lt;span class="o"&gt;+&lt;/span&gt;
        &lt;span class="s"&gt;"FROM users u WHERE u.is_active = 1"&lt;/span&gt;&lt;span class="o"&gt;,&lt;/span&gt;
        &lt;span class="nc"&gt;Tuple&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;class&lt;/span&gt;
    &lt;span class="o"&gt;).&lt;/span&gt;&lt;span class="na"&gt;getResultList&lt;/span&gt;&lt;span class="o"&gt;();&lt;/span&gt;

    &lt;span class="nc"&gt;List&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="nc"&gt;UserDto&lt;/span&gt;&lt;span class="o"&gt;&amp;gt;&lt;/span&gt; &lt;span class="n"&gt;dtos&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="k"&gt;new&lt;/span&gt; &lt;span class="nc"&gt;ArrayList&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&amp;gt;();&lt;/span&gt;

    &lt;span class="k"&gt;for&lt;/span&gt; &lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="nc"&gt;Tuple&lt;/span&gt; &lt;span class="n"&gt;t&lt;/span&gt; &lt;span class="o"&gt;:&lt;/span&gt; &lt;span class="n"&gt;tuples&lt;/span&gt;&lt;span class="o"&gt;)&lt;/span&gt; &lt;span class="o"&gt;{&lt;/span&gt;
        &lt;span class="c1"&gt;// 2. Fetch by name and type. No casting needed.&lt;/span&gt;
        &lt;span class="nc"&gt;Long&lt;/span&gt; &lt;span class="n"&gt;id&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;t&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;get&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="s"&gt;"id"&lt;/span&gt;&lt;span class="o"&gt;,&lt;/span&gt; &lt;span class="nc"&gt;Long&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;class&lt;/span&gt;&lt;span class="o"&gt;);&lt;/span&gt;
        &lt;span class="nc"&gt;String&lt;/span&gt; &lt;span class="n"&gt;username&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;t&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;get&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="s"&gt;"username"&lt;/span&gt;&lt;span class="o"&gt;,&lt;/span&gt; &lt;span class="nc"&gt;String&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;class&lt;/span&gt;&lt;span class="o"&gt;);&lt;/span&gt;
        &lt;span class="nc"&gt;Boolean&lt;/span&gt; &lt;span class="n"&gt;active&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;t&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;get&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="s"&gt;"active"&lt;/span&gt;&lt;span class="o"&gt;,&lt;/span&gt; &lt;span class="nc"&gt;Boolean&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;class&lt;/span&gt;&lt;span class="o"&gt;);&lt;/span&gt;

        &lt;span class="n"&gt;dtos&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;add&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="k"&gt;new&lt;/span&gt; &lt;span class="nc"&gt;UserDto&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="n"&gt;id&lt;/span&gt;&lt;span class="o"&gt;,&lt;/span&gt; &lt;span class="n"&gt;username&lt;/span&gt;&lt;span class="o"&gt;,&lt;/span&gt; &lt;span class="n"&gt;active&lt;/span&gt;&lt;span class="o"&gt;));&lt;/span&gt;
    &lt;span class="o"&gt;}&lt;/span&gt;
    &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="n"&gt;dtos&lt;/span&gt;&lt;span class="o"&gt;;&lt;/span&gt;
&lt;span class="o"&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Using &lt;code&gt;Tuple&lt;/code&gt; makes your intent clear. You are telling the next developer exactly what columns you expect, and you don’t care what order they are in.&lt;/p&gt;

&lt;h2&gt;
  
  
  At the end
&lt;/h2&gt;

&lt;p&gt;That was a tough series of articles. I’m pleased to say that I’ve finally adopted my biggest guide and published it in three separate articles. I’ve more ideas for upcoming articles, and if you enjoy my articles, please connect with me on &lt;a href="https://www.linkedin.com/in/protsenkodev/" rel="noopener noreferrer"&gt;LinkedIn&lt;/a&gt; to stay informed about new content.&lt;/p&gt;

&lt;p&gt;If you missed the previous articles, here they are:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;a href="https://protsenko.dev/spring-data-jpa-best-practices-entity-design-guide/" rel="noopener noreferrer"&gt;Spring Data JPA Best Practices: Entity Design Guide&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="https://protsenko.dev/spring-data-jpa-best-practices-repositories-design-guide/" rel="noopener noreferrer"&gt;Spring Data JPA Best Practices: Repositories Design Guide&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;This post is part of my &lt;a href="https://protsenko.dev/spring-data-jpa-guide/" rel="noopener noreferrer"&gt;Spring Data JPA guide&lt;/a&gt;. Read next: &lt;a href="https://protsenko.dev/spring-data-jpa-batch-insert-performance-tuning/" rel="noopener noreferrer"&gt;Spring Data JPA: Batch Insert Performance Tuning&lt;/a&gt;.&lt;/strong&gt;&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;&lt;strong&gt;Found this useful?&lt;/strong&gt; Follow me on social media to stay updated.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://t.me/protsenko_dev" rel="noopener noreferrer"&gt;Telegram&lt;/a&gt; · &lt;a href="https://www.linkedin.com/in/protsenkodev/" rel="noopener noreferrer"&gt;LinkedIn&lt;/a&gt;&lt;/p&gt;
&lt;/blockquote&gt;

</description>
      <category>java</category>
      <category>springboot</category>
      <category>jpa</category>
      <category>database</category>
    </item>
    <item>
      <title>Spring Data JPA: Batch Insert Performance Tuning</title>
      <dc:creator>Dmitry Protsenko</dc:creator>
      <pubDate>Thu, 05 Nov 2026 15:00:00 +0000</pubDate>
      <link>https://dev.to/protsenko/spring-data-jpa-batch-insert-performance-tuning-140l</link>
      <guid>https://dev.to/protsenko/spring-data-jpa-batch-insert-performance-tuning-140l</guid>
      <description>&lt;p&gt;Two configuration settings improve a slow Hibernate batch insert in Spring Boot Data JPA. Without them, &lt;code&gt;saveAll()&lt;/code&gt; sends one INSERT per row – even across 10,000 rows. With them, median insertion time drops from 437 ms to 77 ms on the same dataset.&lt;/p&gt;

&lt;p&gt;I learned this the hard way. A service I maintained was slow under load, and the root cause was a forgotten Hibernate detail. After fixing it, I shared the finding on &lt;a href="https://www.linkedin.com/posts/protsenkodev_that-small-spring-boot-configuration-improving-share-7452014648624607232-6uP0?utm_source=share&amp;amp;utm_medium=member_desktop&amp;amp;rcm=ACoAADmP3i8BBh0fhPGW0uu8KaL4LN-V1T6n0FI" rel="noopener noreferrer"&gt;LinkedIn&lt;/a&gt; – the post reached 102,000 impressions, 514 reactions, and 394 saves. Clearly, this problem affects many developers.&lt;/p&gt;




&lt;blockquote&gt;
&lt;p&gt;&lt;strong&gt;TL;DR&lt;/strong&gt; – Add &lt;code&gt;hibernate.jdbc.batch_size: 10000 (tune for your load)&lt;/code&gt; to your Hibernate properties and &lt;code&gt;?reWriteBatchedInserts=true&lt;/code&gt; to your datasource URL. These two flags enable Hibernate batch flushing and rewrite individual INSERTs into a single multi-row INSERT. Result: 6x faster bulk inserts compared to untuned JPA saveAll().&lt;/p&gt;
&lt;/blockquote&gt;

&lt;h2&gt;
  
  
  Table of contents
&lt;/h2&gt;

&lt;ul&gt;
&lt;li&gt;Why saveAll() is Slow Without Configuration&lt;/li&gt;
&lt;li&gt;Hibernate Batch Size Configuration&lt;/li&gt;
&lt;li&gt;JDBC batchUpdate (baseline)&lt;/li&gt;
&lt;li&gt;Hibernate StatelessSession&lt;/li&gt;
&lt;li&gt;JPA saveAll()&lt;/li&gt;
&lt;li&gt;EntityManager.persist() loop&lt;/li&gt;
&lt;li&gt;
Testing performance batch inserting with w/wo tuning

&lt;ul&gt;
&lt;li&gt;Before Optimization (no batch_size)&lt;/li&gt;
&lt;li&gt;After Optimization (batch_size: 10000)&lt;/li&gt;
&lt;li&gt;When to Use Each Approach&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;li&gt;At the end&lt;/li&gt;
&lt;/ul&gt;

&lt;h2&gt;
  
  
  Why saveAll() is Slow Without Configuration
&lt;/h2&gt;

&lt;p&gt;By default, Hibernate’s &lt;code&gt;saveAll()&lt;/code&gt; is a plain loop. For each entity, it calls &lt;code&gt;PreparedStatement.execute()&lt;/code&gt; once. Each INSERT is its own round-trip to the database. There is no batching.&lt;/p&gt;

&lt;p&gt;Setting &lt;a href="https://docs.hibernate.org/orm/5.2/userguide/html_single/chapters/batch/Batching.html" rel="noopener noreferrer"&gt;&lt;code&gt;hibernate.jdbc.batch_size&lt;/code&gt;&lt;/a&gt; changes this. Hibernate calls &lt;code&gt;PreparedStatement.addBatch()&lt;/code&gt; for each entity, then calls &lt;code&gt;executeBatch()&lt;/code&gt; once the batch size is reached or at flush time. Instead of N round-trips for N rows, you get &lt;code&gt;ceil(N / batch_size)&lt;/code&gt; round-trips.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://jdbc.postgresql.org/documentation/use/" rel="noopener noreferrer"&gt;&lt;code&gt;reWriteBatchedInserts=true&lt;/code&gt;&lt;/a&gt; on the PostgreSQL JDBC driver takes this further. It rewrites the batched statements into a single multi-row INSERT:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight sql"&gt;&lt;code&gt;&lt;span class="k"&gt;INSERT&lt;/span&gt; &lt;span class="k"&gt;INTO&lt;/span&gt; &lt;span class="n"&gt;items&lt;/span&gt; &lt;span class="k"&gt;VALUES&lt;/span&gt; &lt;span class="p"&gt;(...),&lt;/span&gt; &lt;span class="p"&gt;(...),&lt;/span&gt; &lt;span class="p"&gt;(...)&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;This reduces protocol overhead. It also explains why the JDBC baseline improved from 88 ms to 56 ms between test runs, even though &lt;code&gt;batch_size&lt;/code&gt; does not affect JDBC directly.&lt;/p&gt;

&lt;h2&gt;
  
  
  Hibernate Batch Size Configuration
&lt;/h2&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight yaml"&gt;&lt;code&gt;&lt;span class="na"&gt;spring&lt;/span&gt;&lt;span class="pi"&gt;:&lt;/span&gt;
  &lt;span class="na"&gt;datasource&lt;/span&gt;&lt;span class="pi"&gt;:&lt;/span&gt;
    &lt;span class="na"&gt;url&lt;/span&gt;&lt;span class="pi"&gt;:&lt;/span&gt; &lt;span class="s"&gt;jdbc:postgresql://localhost:5432/postgres?reWriteBatchedInserts=true&lt;/span&gt;
  &lt;span class="na"&gt;jpa&lt;/span&gt;&lt;span class="pi"&gt;:&lt;/span&gt;
    &lt;span class="na"&gt;properties&lt;/span&gt;&lt;span class="pi"&gt;:&lt;/span&gt;
      &lt;span class="na"&gt;hibernate&lt;/span&gt;&lt;span class="pi"&gt;:&lt;/span&gt;
        &lt;span class="na"&gt;jdbc&lt;/span&gt;&lt;span class="pi"&gt;:&lt;/span&gt;
          &lt;span class="na"&gt;batch_size&lt;/span&gt;&lt;span class="pi"&gt;:&lt;/span&gt; &lt;span class="m"&gt;10000&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Set &lt;code&gt;batch_size&lt;/code&gt; to at least the number of rows you expect in a single transaction flush. This benchmark uses 10,000 to cover all rows in one flush without splitting.&lt;/p&gt;

&lt;p&gt;I love Spring Data JPA for the way it helps you maintain a project and deliver features quickly. But there is a lot of magic under the hood – and hibernate batch size configuration is one of those things you need to know about.&lt;/p&gt;

&lt;p&gt;For testing this and other batch configurations, I compared four approaches:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;strong&gt;JDBC batchUpdate&lt;/strong&gt; – raw SQL with &lt;code&gt;jdbcTemplate.batchUpdate()&lt;/code&gt;, the performance baseline&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Hibernate StatelessSession&lt;/strong&gt; – &lt;code&gt;statelessSession.insertMultiple()&lt;/code&gt;, bypasses the first-level cache&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;JPA saveAll()&lt;/strong&gt; – Spring Data JPA repository with &lt;code&gt;batch_size&lt;/code&gt; configured&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;EntityManager loop&lt;/strong&gt; – &lt;code&gt;entityManager.persist()&lt;/code&gt; in a loop, &lt;code&gt;batch_size&lt;/code&gt; configured&lt;/li&gt;
&lt;/ul&gt;




&lt;h2&gt;
  
  
  JDBC batchUpdate (baseline)
&lt;/h2&gt;

&lt;p&gt;Classic JDBC using &lt;code&gt;jdbcTemplate.batchUpdate()&lt;/code&gt;. The driver collects all rows and sends them in one round-trip. No Hibernate is involved, so &lt;code&gt;batch_size&lt;/code&gt; has no effect – batching is always on.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight java"&gt;&lt;code&gt;&lt;span class="nd"&gt;@Transactional&lt;/span&gt;
&lt;span class="kd"&gt;public&lt;/span&gt; &lt;span class="nc"&gt;Order&lt;/span&gt; &lt;span class="nf"&gt;createOrder&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="nc"&gt;CreateOrderCommand&lt;/span&gt; &lt;span class="n"&gt;command&lt;/span&gt;&lt;span class="o"&gt;)&lt;/span&gt; &lt;span class="o"&gt;{&lt;/span&gt;
    &lt;span class="no"&gt;UUID&lt;/span&gt; &lt;span class="n"&gt;orderId&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="no"&gt;UUID&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;randomUUID&lt;/span&gt;&lt;span class="o"&gt;();&lt;/span&gt;
    &lt;span class="nc"&gt;Instant&lt;/span&gt; &lt;span class="n"&gt;now&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nc"&gt;Instant&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;now&lt;/span&gt;&lt;span class="o"&gt;();&lt;/span&gt;
    &lt;span class="nc"&gt;Timestamp&lt;/span&gt; &lt;span class="n"&gt;nowTs&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nc"&gt;Timestamp&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;from&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="n"&gt;now&lt;/span&gt;&lt;span class="o"&gt;);&lt;/span&gt;

    &lt;span class="n"&gt;jdbcTemplate&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;update&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="no"&gt;INSERT_ORDER_SQL&lt;/span&gt;&lt;span class="o"&gt;,&lt;/span&gt; &lt;span class="n"&gt;orderId&lt;/span&gt;&lt;span class="o"&gt;,&lt;/span&gt; &lt;span class="n"&gt;command&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;userId&lt;/span&gt;&lt;span class="o"&gt;(),&lt;/span&gt; &lt;span class="n"&gt;nowTs&lt;/span&gt;&lt;span class="o"&gt;,&lt;/span&gt; &lt;span class="n"&gt;nowTs&lt;/span&gt;&lt;span class="o"&gt;);&lt;/span&gt;

    &lt;span class="nc"&gt;List&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="nc"&gt;CreateOrderCommand&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;ItemEntry&lt;/span&gt;&lt;span class="o"&gt;&amp;gt;&lt;/span&gt; &lt;span class="n"&gt;entries&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;command&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;items&lt;/span&gt;&lt;span class="o"&gt;();&lt;/span&gt;
    &lt;span class="n"&gt;jdbcTemplate&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;batchUpdate&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="no"&gt;INSERT_ITEM_SQL&lt;/span&gt;&lt;span class="o"&gt;,&lt;/span&gt; &lt;span class="n"&gt;entries&lt;/span&gt;&lt;span class="o"&gt;,&lt;/span&gt; &lt;span class="n"&gt;entries&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;size&lt;/span&gt;&lt;span class="o"&gt;(),&lt;/span&gt; &lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="n"&gt;ps&lt;/span&gt;&lt;span class="o"&gt;,&lt;/span&gt; &lt;span class="n"&gt;entry&lt;/span&gt;&lt;span class="o"&gt;)&lt;/span&gt; &lt;span class="o"&gt;-&amp;gt;&lt;/span&gt; &lt;span class="o"&gt;{&lt;/span&gt;
        &lt;span class="n"&gt;ps&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;setObject&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;1&lt;/span&gt;&lt;span class="o"&gt;,&lt;/span&gt; &lt;span class="n"&gt;entry&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;id&lt;/span&gt;&lt;span class="o"&gt;().&lt;/span&gt;&lt;span class="na"&gt;getItemId&lt;/span&gt;&lt;span class="o"&gt;());&lt;/span&gt;
        &lt;span class="n"&gt;ps&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;setObject&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;2&lt;/span&gt;&lt;span class="o"&gt;,&lt;/span&gt; &lt;span class="n"&gt;entry&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;id&lt;/span&gt;&lt;span class="o"&gt;().&lt;/span&gt;&lt;span class="na"&gt;getStoreId&lt;/span&gt;&lt;span class="o"&gt;());&lt;/span&gt;
        &lt;span class="n"&gt;ps&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;setObject&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;3&lt;/span&gt;&lt;span class="o"&gt;,&lt;/span&gt; &lt;span class="n"&gt;orderId&lt;/span&gt;&lt;span class="o"&gt;);&lt;/span&gt;
        &lt;span class="n"&gt;ps&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;setString&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;4&lt;/span&gt;&lt;span class="o"&gt;,&lt;/span&gt; &lt;span class="n"&gt;entry&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;name&lt;/span&gt;&lt;span class="o"&gt;());&lt;/span&gt;
        &lt;span class="n"&gt;ps&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;setInt&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;5&lt;/span&gt;&lt;span class="o"&gt;,&lt;/span&gt; &lt;span class="n"&gt;entry&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;quantity&lt;/span&gt;&lt;span class="o"&gt;());&lt;/span&gt;
        &lt;span class="n"&gt;ps&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;setBigDecimal&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;6&lt;/span&gt;&lt;span class="o"&gt;,&lt;/span&gt; &lt;span class="n"&gt;entry&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;cost&lt;/span&gt;&lt;span class="o"&gt;());&lt;/span&gt;
    &lt;span class="o"&gt;});&lt;/span&gt;

    &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="k"&gt;new&lt;/span&gt; &lt;span class="nf"&gt;Order&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="n"&gt;orderId&lt;/span&gt;&lt;span class="o"&gt;,&lt;/span&gt; &lt;span class="n"&gt;command&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;userId&lt;/span&gt;&lt;span class="o"&gt;(),&lt;/span&gt; &lt;span class="n"&gt;now&lt;/span&gt;&lt;span class="o"&gt;,&lt;/span&gt; &lt;span class="n"&gt;now&lt;/span&gt;&lt;span class="o"&gt;);&lt;/span&gt;
&lt;span class="o"&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;






&lt;h2&gt;
  
  
  Hibernate StatelessSession
&lt;/h2&gt;

&lt;p&gt;&lt;code&gt;StatelessSession&lt;/code&gt; skips the first-level cache, dirty-checking, and lifecycle callbacks. The &lt;code&gt;insertMultiple()&lt;/code&gt; API hands all entities to Hibernate’s batch machinery in one call.&lt;/p&gt;

&lt;p&gt;Key finding: without &lt;code&gt;batch_size&lt;/code&gt;, StatelessSession is just as slow as JPA. The batching still relies on that configuration. The API is not the lever – the config is.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight java"&gt;&lt;code&gt;&lt;span class="nd"&gt;@Transactional&lt;/span&gt;
&lt;span class="kd"&gt;public&lt;/span&gt; &lt;span class="nc"&gt;Order&lt;/span&gt; &lt;span class="nf"&gt;createOrder&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="nc"&gt;CreateOrderCommand&lt;/span&gt; &lt;span class="n"&gt;command&lt;/span&gt;&lt;span class="o"&gt;)&lt;/span&gt; &lt;span class="o"&gt;{&lt;/span&gt;
    &lt;span class="nc"&gt;Order&lt;/span&gt; &lt;span class="n"&gt;order&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="k"&gt;new&lt;/span&gt; &lt;span class="nc"&gt;Order&lt;/span&gt;&lt;span class="o"&gt;();&lt;/span&gt;
    &lt;span class="n"&gt;order&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;setUserId&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="n"&gt;command&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;userId&lt;/span&gt;&lt;span class="o"&gt;());&lt;/span&gt;

    &lt;span class="nc"&gt;Session&lt;/span&gt; &lt;span class="n"&gt;session&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;entityManager&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;unwrap&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="nc"&gt;Session&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;class&lt;/span&gt;&lt;span class="o"&gt;);&lt;/span&gt;
    &lt;span class="k"&gt;try&lt;/span&gt; &lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="nc"&gt;StatelessSession&lt;/span&gt; &lt;span class="n"&gt;statelessSession&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;session&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;statelessWithOptions&lt;/span&gt;&lt;span class="o"&gt;().&lt;/span&gt;&lt;span class="na"&gt;connection&lt;/span&gt;&lt;span class="o"&gt;().&lt;/span&gt;&lt;span class="na"&gt;open&lt;/span&gt;&lt;span class="o"&gt;())&lt;/span&gt; &lt;span class="o"&gt;{&lt;/span&gt;
        &lt;span class="n"&gt;statelessSession&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;insert&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="n"&gt;order&lt;/span&gt;&lt;span class="o"&gt;);&lt;/span&gt;

        &lt;span class="nc"&gt;List&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="nc"&gt;Item&lt;/span&gt;&lt;span class="o"&gt;&amp;gt;&lt;/span&gt; &lt;span class="n"&gt;items&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="k"&gt;new&lt;/span&gt; &lt;span class="nc"&gt;ArrayList&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&amp;gt;(&lt;/span&gt;&lt;span class="n"&gt;command&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;items&lt;/span&gt;&lt;span class="o"&gt;().&lt;/span&gt;&lt;span class="na"&gt;size&lt;/span&gt;&lt;span class="o"&gt;());&lt;/span&gt;
        &lt;span class="k"&gt;for&lt;/span&gt; &lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="nc"&gt;CreateOrderCommand&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;ItemEntry&lt;/span&gt; &lt;span class="n"&gt;item&lt;/span&gt; &lt;span class="o"&gt;:&lt;/span&gt; &lt;span class="n"&gt;command&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;items&lt;/span&gt;&lt;span class="o"&gt;())&lt;/span&gt; &lt;span class="o"&gt;{&lt;/span&gt;
            &lt;span class="n"&gt;items&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;add&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="k"&gt;new&lt;/span&gt; &lt;span class="nc"&gt;Item&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="n"&gt;item&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;id&lt;/span&gt;&lt;span class="o"&gt;(),&lt;/span&gt; &lt;span class="n"&gt;order&lt;/span&gt;&lt;span class="o"&gt;,&lt;/span&gt; &lt;span class="n"&gt;item&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;name&lt;/span&gt;&lt;span class="o"&gt;(),&lt;/span&gt; &lt;span class="n"&gt;item&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;quantity&lt;/span&gt;&lt;span class="o"&gt;(),&lt;/span&gt; &lt;span class="n"&gt;item&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;cost&lt;/span&gt;&lt;span class="o"&gt;()));&lt;/span&gt;
        &lt;span class="o"&gt;}&lt;/span&gt;
        &lt;span class="n"&gt;statelessSession&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;insertMultiple&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="n"&gt;items&lt;/span&gt;&lt;span class="o"&gt;);&lt;/span&gt;
    &lt;span class="o"&gt;}&lt;/span&gt;

    &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="n"&gt;order&lt;/span&gt;&lt;span class="o"&gt;;&lt;/span&gt;
&lt;span class="o"&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;






&lt;h2&gt;
  
  
  JPA saveAll()
&lt;/h2&gt;

&lt;p&gt;Standard Spring Data JPA. Without &lt;code&gt;batch_size&lt;/code&gt;, &lt;code&gt;saveAll()&lt;/code&gt; sends one INSERT per row. With it, Hibernate accumulates statements and flushes them in batches.&lt;/p&gt;

&lt;p&gt;One important detail: the entity implements &lt;a href="https://docs.spring.io/spring-data/jpa/reference/jpa/entity-persistence.html" rel="noopener noreferrer"&gt;&lt;code&gt;Persistable&amp;lt;ItemId&amp;gt;&lt;/code&gt;&lt;/a&gt; and tracks &lt;code&gt;isNew&lt;/code&gt; manually. Without this, Hibernate issues a SELECT before each INSERT to check whether the entity exists. It cannot determine new vs. existing from a composite ID alone – so it queries first. That turns a bulk insert into an N+1 SELECT problem.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight java"&gt;&lt;code&gt;&lt;span class="nd"&gt;@Transactional&lt;/span&gt;
&lt;span class="kd"&gt;public&lt;/span&gt; &lt;span class="nc"&gt;Order&lt;/span&gt; &lt;span class="nf"&gt;createOrder&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="nc"&gt;CreateOrderCommand&lt;/span&gt; &lt;span class="n"&gt;command&lt;/span&gt;&lt;span class="o"&gt;)&lt;/span&gt; &lt;span class="o"&gt;{&lt;/span&gt;
    &lt;span class="nc"&gt;Order&lt;/span&gt; &lt;span class="n"&gt;order&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="k"&gt;new&lt;/span&gt; &lt;span class="nc"&gt;Order&lt;/span&gt;&lt;span class="o"&gt;();&lt;/span&gt;
    &lt;span class="n"&gt;order&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;setUserId&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="n"&gt;command&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;userId&lt;/span&gt;&lt;span class="o"&gt;());&lt;/span&gt;

    &lt;span class="nc"&gt;Order&lt;/span&gt; &lt;span class="n"&gt;savedOrder&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;orderRepository&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;save&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="n"&gt;order&lt;/span&gt;&lt;span class="o"&gt;);&lt;/span&gt;

    &lt;span class="nc"&gt;List&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="nc"&gt;Item&lt;/span&gt;&lt;span class="o"&gt;&amp;gt;&lt;/span&gt; &lt;span class="n"&gt;items&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;command&lt;/span&gt;
            &lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;items&lt;/span&gt;&lt;span class="o"&gt;()&lt;/span&gt;
            &lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;stream&lt;/span&gt;&lt;span class="o"&gt;()&lt;/span&gt;
            &lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;map&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="n"&gt;item&lt;/span&gt; &lt;span class="o"&gt;-&amp;gt;&lt;/span&gt; &lt;span class="k"&gt;new&lt;/span&gt; &lt;span class="nc"&gt;Item&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="n"&gt;item&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;id&lt;/span&gt;&lt;span class="o"&gt;(),&lt;/span&gt; &lt;span class="n"&gt;savedOrder&lt;/span&gt;&lt;span class="o"&gt;,&lt;/span&gt; &lt;span class="n"&gt;item&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;name&lt;/span&gt;&lt;span class="o"&gt;(),&lt;/span&gt; &lt;span class="n"&gt;item&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;quantity&lt;/span&gt;&lt;span class="o"&gt;(),&lt;/span&gt; &lt;span class="n"&gt;item&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;cost&lt;/span&gt;&lt;span class="o"&gt;()))&lt;/span&gt;
            &lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;toList&lt;/span&gt;&lt;span class="o"&gt;();&lt;/span&gt;

    &lt;span class="n"&gt;itemRepository&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;saveAll&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="n"&gt;items&lt;/span&gt;&lt;span class="o"&gt;);&lt;/span&gt;

    &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="n"&gt;savedOrder&lt;/span&gt;&lt;span class="o"&gt;;&lt;/span&gt;
&lt;span class="o"&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;





&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight java"&gt;&lt;code&gt;&lt;span class="nd"&gt;@Immutable&lt;/span&gt;
&lt;span class="nd"&gt;@Entity&lt;/span&gt;
&lt;span class="nd"&gt;@Table&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="n"&gt;name&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="s"&gt;"items"&lt;/span&gt;&lt;span class="o"&gt;)&lt;/span&gt;
&lt;span class="kd"&gt;public&lt;/span&gt; &lt;span class="kd"&gt;class&lt;/span&gt; &lt;span class="nc"&gt;Item&lt;/span&gt; &lt;span class="kd"&gt;implements&lt;/span&gt; &lt;span class="nc"&gt;Persistable&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="nc"&gt;ItemId&lt;/span&gt;&lt;span class="o"&gt;&amp;gt;&lt;/span&gt; &lt;span class="o"&gt;{&lt;/span&gt;

    &lt;span class="nd"&gt;@EmbeddedId&lt;/span&gt;
    &lt;span class="kd"&gt;private&lt;/span&gt; &lt;span class="nc"&gt;ItemId&lt;/span&gt; &lt;span class="n"&gt;id&lt;/span&gt;&lt;span class="o"&gt;;&lt;/span&gt;

    &lt;span class="nd"&gt;@Transient&lt;/span&gt;
    &lt;span class="kd"&gt;private&lt;/span&gt; &lt;span class="kt"&gt;boolean&lt;/span&gt; &lt;span class="n"&gt;isNew&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="kc"&gt;true&lt;/span&gt;&lt;span class="o"&gt;;&lt;/span&gt;

    &lt;span class="nd"&gt;@ManyToOne&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="n"&gt;fetch&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nc"&gt;FetchType&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;LAZY&lt;/span&gt;&lt;span class="o"&gt;)&lt;/span&gt;
    &lt;span class="nd"&gt;@JoinColumn&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="n"&gt;name&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="s"&gt;"order_id"&lt;/span&gt;&lt;span class="o"&gt;,&lt;/span&gt; &lt;span class="n"&gt;nullable&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="kc"&gt;false&lt;/span&gt;&lt;span class="o"&gt;)&lt;/span&gt;
    &lt;span class="kd"&gt;private&lt;/span&gt; &lt;span class="nc"&gt;Order&lt;/span&gt; &lt;span class="n"&gt;order&lt;/span&gt;&lt;span class="o"&gt;;&lt;/span&gt;

    &lt;span class="nd"&gt;@Column&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="n"&gt;nullable&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="kc"&gt;false&lt;/span&gt;&lt;span class="o"&gt;)&lt;/span&gt;
    &lt;span class="kd"&gt;private&lt;/span&gt; &lt;span class="nc"&gt;String&lt;/span&gt; &lt;span class="n"&gt;name&lt;/span&gt;&lt;span class="o"&gt;;&lt;/span&gt;

    &lt;span class="nd"&gt;@Column&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="n"&gt;nullable&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="kc"&gt;false&lt;/span&gt;&lt;span class="o"&gt;)&lt;/span&gt;
    &lt;span class="kd"&gt;private&lt;/span&gt; &lt;span class="kt"&gt;int&lt;/span&gt; &lt;span class="n"&gt;quantity&lt;/span&gt;&lt;span class="o"&gt;;&lt;/span&gt;

    &lt;span class="nd"&gt;@Column&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="n"&gt;nullable&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="kc"&gt;false&lt;/span&gt;&lt;span class="o"&gt;,&lt;/span&gt; &lt;span class="n"&gt;precision&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="mi"&gt;19&lt;/span&gt;&lt;span class="o"&gt;,&lt;/span&gt; &lt;span class="n"&gt;scale&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="mi"&gt;2&lt;/span&gt;&lt;span class="o"&gt;)&lt;/span&gt;
    &lt;span class="kd"&gt;private&lt;/span&gt; &lt;span class="nc"&gt;BigDecimal&lt;/span&gt; &lt;span class="n"&gt;cost&lt;/span&gt;&lt;span class="o"&gt;;&lt;/span&gt;

    &lt;span class="c1"&gt;// ... constructor, getters&lt;/span&gt;

    &lt;span class="nd"&gt;@Override&lt;/span&gt;
    &lt;span class="kd"&gt;public&lt;/span&gt; &lt;span class="kt"&gt;boolean&lt;/span&gt; &lt;span class="nf"&gt;isNew&lt;/span&gt;&lt;span class="o"&gt;()&lt;/span&gt; &lt;span class="o"&gt;{&lt;/span&gt;
        &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="n"&gt;isNew&lt;/span&gt;&lt;span class="o"&gt;;&lt;/span&gt;
    &lt;span class="o"&gt;}&lt;/span&gt;

    &lt;span class="nd"&gt;@PostPersist&lt;/span&gt;
    &lt;span class="nd"&gt;@PostLoad&lt;/span&gt;
    &lt;span class="kd"&gt;private&lt;/span&gt; &lt;span class="kt"&gt;void&lt;/span&gt; &lt;span class="nf"&gt;markNotNew&lt;/span&gt;&lt;span class="o"&gt;()&lt;/span&gt; &lt;span class="o"&gt;{&lt;/span&gt;
        &lt;span class="k"&gt;this&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;isNew&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="kc"&gt;false&lt;/span&gt;&lt;span class="o"&gt;;&lt;/span&gt;
    &lt;span class="o"&gt;}&lt;/span&gt;
&lt;span class="o"&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;






&lt;h2&gt;
  
  
  EntityManager.persist() loop
&lt;/h2&gt;

&lt;p&gt;Direct JPA EntityManager. Hibernate accumulates &lt;code&gt;persist()&lt;/code&gt; calls and flushes them in batches because &lt;code&gt;batch_size&lt;/code&gt; is set.&lt;/p&gt;

&lt;p&gt;Unlike StatelessSession, the persistence context (first-level cache) is active. All 10,000 entities are tracked until the transaction commits, adding a fixed overhead at flush time.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight java"&gt;&lt;code&gt;&lt;span class="nd"&gt;@Transactional&lt;/span&gt;
&lt;span class="kd"&gt;public&lt;/span&gt; &lt;span class="nc"&gt;Order&lt;/span&gt; &lt;span class="nf"&gt;createOrder&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="nc"&gt;CreateOrderCommand&lt;/span&gt; &lt;span class="n"&gt;command&lt;/span&gt;&lt;span class="o"&gt;)&lt;/span&gt; &lt;span class="o"&gt;{&lt;/span&gt;
    &lt;span class="nc"&gt;Order&lt;/span&gt; &lt;span class="n"&gt;order&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="k"&gt;new&lt;/span&gt; &lt;span class="nc"&gt;Order&lt;/span&gt;&lt;span class="o"&gt;();&lt;/span&gt;
    &lt;span class="n"&gt;order&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;setUserId&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="n"&gt;command&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;userId&lt;/span&gt;&lt;span class="o"&gt;());&lt;/span&gt;
    &lt;span class="n"&gt;entityManager&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;persist&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="n"&gt;order&lt;/span&gt;&lt;span class="o"&gt;);&lt;/span&gt;

    &lt;span class="k"&gt;for&lt;/span&gt; &lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="nc"&gt;CreateOrderCommand&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;ItemEntry&lt;/span&gt; &lt;span class="n"&gt;item&lt;/span&gt; &lt;span class="o"&gt;:&lt;/span&gt; &lt;span class="n"&gt;command&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;items&lt;/span&gt;&lt;span class="o"&gt;())&lt;/span&gt; &lt;span class="o"&gt;{&lt;/span&gt;
        &lt;span class="n"&gt;entityManager&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;persist&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="k"&gt;new&lt;/span&gt; &lt;span class="nc"&gt;Item&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="n"&gt;item&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;id&lt;/span&gt;&lt;span class="o"&gt;(),&lt;/span&gt; &lt;span class="n"&gt;order&lt;/span&gt;&lt;span class="o"&gt;,&lt;/span&gt; &lt;span class="n"&gt;item&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;name&lt;/span&gt;&lt;span class="o"&gt;(),&lt;/span&gt; &lt;span class="n"&gt;item&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;quantity&lt;/span&gt;&lt;span class="o"&gt;(),&lt;/span&gt; &lt;span class="n"&gt;item&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;cost&lt;/span&gt;&lt;span class="o"&gt;()));&lt;/span&gt;
    &lt;span class="o"&gt;}&lt;/span&gt;

    &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="n"&gt;order&lt;/span&gt;&lt;span class="o"&gt;;&lt;/span&gt;
&lt;span class="o"&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;






&lt;h2&gt;
  
  
  Testing performance batch inserting with w/wo tuning
&lt;/h2&gt;

&lt;p&gt;10 runs per approach (2 warmup runs excluded from measurements), inserting 10,000 entries per run. The database was cleaned between each run. Hardware: Apple M4 Pro 24 GB, JDK 21, PostgreSQL 17.&lt;/p&gt;

&lt;h3&gt;
  
  
  Before Optimization (no batch_size)
&lt;/h3&gt;

&lt;div class="table-wrapper-paragraph"&gt;&lt;table&gt;
&lt;thead&gt;
&lt;tr&gt;
&lt;th&gt;Approach&lt;/th&gt;
&lt;th&gt;Min (ms)&lt;/th&gt;
&lt;th&gt;Max (ms)&lt;/th&gt;
&lt;th&gt;Avg (ms)&lt;/th&gt;
&lt;th&gt;Median (ms)&lt;/th&gt;
&lt;th&gt;% vs fastest&lt;/th&gt;
&lt;/tr&gt;
&lt;/thead&gt;
&lt;tbody&gt;
&lt;tr&gt;
&lt;td&gt;JDBC template&lt;/td&gt;
&lt;td&gt;81&lt;/td&gt;
&lt;td&gt;191&lt;/td&gt;
&lt;td&gt;97.40&lt;/td&gt;
&lt;td&gt;88.00&lt;/td&gt;
&lt;td&gt;0%&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;StatelessSession.insertMultiple()&lt;/td&gt;
&lt;td&gt;404&lt;/td&gt;
&lt;td&gt;635&lt;/td&gt;
&lt;td&gt;441.70&lt;/td&gt;
&lt;td&gt;423.00&lt;/td&gt;
&lt;td&gt;381%&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;JPA saveAll()&lt;/td&gt;
&lt;td&gt;424&lt;/td&gt;
&lt;td&gt;628&lt;/td&gt;
&lt;td&gt;464.30&lt;/td&gt;
&lt;td&gt;436.50&lt;/td&gt;
&lt;td&gt;396%&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;EntityManager.persist() loop&lt;/td&gt;
&lt;td&gt;421&lt;/td&gt;
&lt;td&gt;491&lt;/td&gt;
&lt;td&gt;442.40&lt;/td&gt;
&lt;td&gt;437.50&lt;/td&gt;
&lt;td&gt;397%&lt;/td&gt;
&lt;/tr&gt;
&lt;/tbody&gt;
&lt;/table&gt;&lt;/div&gt;

&lt;h3&gt;
  
  
  After Optimization (batch_size: 10000)
&lt;/h3&gt;

&lt;div class="table-wrapper-paragraph"&gt;&lt;table&gt;
&lt;thead&gt;
&lt;tr&gt;
&lt;th&gt;Approach&lt;/th&gt;
&lt;th&gt;Min (ms)&lt;/th&gt;
&lt;th&gt;Max (ms)&lt;/th&gt;
&lt;th&gt;Avg (ms)&lt;/th&gt;
&lt;th&gt;Median (ms)&lt;/th&gt;
&lt;th&gt;% vs fastest&lt;/th&gt;
&lt;/tr&gt;
&lt;/thead&gt;
&lt;tbody&gt;
&lt;tr&gt;
&lt;td&gt;JDBC template&lt;/td&gt;
&lt;td&gt;54&lt;/td&gt;
&lt;td&gt;91&lt;/td&gt;
&lt;td&gt;59.50&lt;/td&gt;
&lt;td&gt;55.50&lt;/td&gt;
&lt;td&gt;0%&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;StatelessSession.insertMultiple()&lt;/td&gt;
&lt;td&gt;62&lt;/td&gt;
&lt;td&gt;163&lt;/td&gt;
&lt;td&gt;74.60&lt;/td&gt;
&lt;td&gt;65.00&lt;/td&gt;
&lt;td&gt;17%&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;EntityManager.persist() loop&lt;/td&gt;
&lt;td&gt;73&lt;/td&gt;
&lt;td&gt;115&lt;/td&gt;
&lt;td&gt;81.60&lt;/td&gt;
&lt;td&gt;75.50&lt;/td&gt;
&lt;td&gt;36%&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;JPA saveAll()&lt;/td&gt;
&lt;td&gt;73&lt;/td&gt;
&lt;td&gt;214&lt;/td&gt;
&lt;td&gt;94.60&lt;/td&gt;
&lt;td&gt;77.00&lt;/td&gt;
&lt;td&gt;39%&lt;/td&gt;
&lt;/tr&gt;
&lt;/tbody&gt;
&lt;/table&gt;&lt;/div&gt;

&lt;p&gt;With the optimization, the median for JPA &lt;code&gt;saveAll()&lt;/code&gt; drops to 77 ms vs. 55 ms for raw JDBC. The extra 22 ms is JPA overhead – the cost of working at a higher level of abstraction. For most use cases, it is an acceptable trade-off.&lt;/p&gt;

&lt;p&gt;One more finding worth noting: StatelessSession.insertMultiple() dropped from 423 ms to 65 ms with the same &lt;code&gt;batch_size&lt;/code&gt; config. Without it, even the “bypass everything” Hibernate API sends one INSERT per row. The configuration is the lever, not which API you choose&lt;/p&gt;

&lt;h3&gt;
  
  
  When to Use Each Approach
&lt;/h3&gt;

&lt;div class="table-wrapper-paragraph"&gt;&lt;table&gt;
&lt;thead&gt;
&lt;tr&gt;
&lt;th&gt;Situation&lt;/th&gt;
&lt;th&gt;Recommended Approach&lt;/th&gt;
&lt;/tr&gt;
&lt;/thead&gt;
&lt;tbody&gt;
&lt;tr&gt;
&lt;td&gt;Standard JPA, simplest code&lt;/td&gt;
&lt;td&gt;
&lt;code&gt;saveAll()&lt;/code&gt; + &lt;code&gt;batch_size&lt;/code&gt;
&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;Composite key entities&lt;/td&gt;
&lt;td&gt;
&lt;code&gt;saveAll()&lt;/code&gt; + &lt;code&gt;Persistable&amp;lt;&amp;gt;&lt;/code&gt; implementation&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;Bypass first-level cache overhead&lt;/td&gt;
&lt;td&gt;&lt;code&gt;StatelessSession.insertMultiple()&lt;/code&gt;&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;Maximum throughput, no ORM overhead&lt;/td&gt;
&lt;td&gt;JDBC &lt;code&gt;batchUpdate()&lt;/code&gt;
&lt;/td&gt;
&lt;/tr&gt;
&lt;/tbody&gt;
&lt;/table&gt;&lt;/div&gt;

&lt;h2&gt;
  
  
  At the end
&lt;/h2&gt;

&lt;p&gt;If you like this post, follow me on &lt;a href="https://www.linkedin.com/in/protsenkodev/" rel="noopener noreferrer"&gt;LinkedIn&lt;/a&gt; to get to know about new articles and quality posts on software development.&lt;/p&gt;

&lt;p&gt;If you’re interested in Spring Data JPA content, I have more. Just take the time and open &lt;a href="https://protsenko.dev/category/spring-data-jpa/" rel="noopener noreferrer"&gt;Spring Data JPA&lt;/a&gt; posts. I highly recommend my latest article: &lt;a href="https://protsenko.dev/spring-data-jpa-with-kotlin-best-practices-for-spring-boot/" rel="noopener noreferrer"&gt;Spring Data JPA with Kotlin: Best Practices for Spring Boot&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;This post is part of my &lt;a href="https://protsenko.dev/spring-data-jpa-guide/" rel="noopener noreferrer"&gt;Spring Data JPA guide&lt;/a&gt;. Read next: &lt;a href="https://protsenko.dev/spring-data-jpa-with-kotlin-best-practices-for-spring-boot/" rel="noopener noreferrer"&gt;Spring Data JPA with Kotlin: Entities, Repositories, and Pitfalls&lt;/a&gt;.&lt;/strong&gt;&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;&lt;strong&gt;Found this useful?&lt;/strong&gt; Follow me on social media to stay updated.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://t.me/protsenko_dev" rel="noopener noreferrer"&gt;Telegram&lt;/a&gt; · &lt;a href="https://www.linkedin.com/in/protsenkodev/" rel="noopener noreferrer"&gt;LinkedIn&lt;/a&gt;&lt;/p&gt;
&lt;/blockquote&gt;

</description>
      <category>java</category>
      <category>springboot</category>
      <category>jpa</category>
      <category>performance</category>
    </item>
    <item>
      <title>Spring Data JPA with Kotlin: Entities, Repositories, and Pitfalls</title>
      <dc:creator>Dmitry Protsenko</dc:creator>
      <pubDate>Wed, 04 Nov 2026 15:00:00 +0000</pubDate>
      <link>https://dev.to/protsenko/spring-data-jpa-with-kotlin-entities-repositories-and-pitfalls-2c2e</link>
      <guid>https://dev.to/protsenko/spring-data-jpa-with-kotlin-entities-repositories-and-pitfalls-2c2e</guid>
      <description>&lt;p&gt;This guide covers Spring Data JPA with Kotlin for Spring Boot 4.x projects — from JPA in Spring Boot setup and entity modeling to Spring Data JPA repositories, projections, pagination, and dynamic filtering. Every Spring Boot JPA example uses idiomatic Kotlin.&lt;/p&gt;

&lt;p&gt;Spring Boot is the framework layer that lets you build production-ready apps quickly, with auto-configuration, an embedded server, sensible defaults, and fewer manual setup steps.&lt;/p&gt;

&lt;p&gt;Spring Data JPA is the persistence layer that sits on top of JPA/Hibernate and provides repository APIs for common database tasks (CRUD, pagination, query methods) without requiring you to write boilerplate DAO code.&lt;/p&gt;

&lt;p&gt;Kotlin improves this workflow by making backend code shorter and safer:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Null-safety reduces a large class of runtime null errors.&lt;/li&gt;
&lt;li&gt;Data/DTO modeling is concise and readable.&lt;/li&gt;
&lt;li&gt;Extension functions and expressive syntax keep service/repository code easier to maintain.&lt;/li&gt;
&lt;/ul&gt;

&lt;h2&gt;
  
  
  Table of contents
&lt;/h2&gt;

&lt;ul&gt;
&lt;li&gt;Start your Kotlin project with Spring Initializr&lt;/li&gt;
&lt;li&gt;
JPA Entity Basics in Kotlin: @Entity, @Id, @Column

&lt;ul&gt;
&lt;li&gt;@Entity&lt;/li&gt;
&lt;li&gt;@Id&lt;/li&gt;
&lt;li&gt;@EmbeddedId&lt;/li&gt;
&lt;li&gt;@Column(…) (optional)&lt;/li&gt;
&lt;li&gt;No-arg constructor requirement&lt;/li&gt;
&lt;li&gt;Mapping Domain States with Enums&lt;/li&gt;
&lt;li&gt;Overriding equals and hashCode in JPA Entities&lt;/li&gt;
&lt;li&gt;Best Practices for Designing JPA Entities&lt;/li&gt;
&lt;li&gt;Can a Kotlin data class be a JPA entity?&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;li&gt;
Accessing Data with JpaRepository and CrudRepository

&lt;ul&gt;
&lt;li&gt;JPQL and @Query: Querying Data with Spring Data JPA&lt;/li&gt;
&lt;li&gt;Updating data in repositories&lt;/li&gt;
&lt;li&gt;Kotlin-Idiomatic Entity Fetching with Spring Data JPA&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;li&gt;
Pagination in Spring Boot: Pageable, Page, and Slice

&lt;ul&gt;
&lt;li&gt;Page vs Slice vs List&lt;/li&gt;
&lt;li&gt;Pageable and PageRequest&lt;/li&gt;
&lt;li&gt;Sort&lt;/li&gt;
&lt;li&gt;Type-safe sort with JpaSort and TypedSort&lt;/li&gt;
&lt;li&gt;Repository method signatures&lt;/li&gt;
&lt;li&gt;Count query optimization&lt;/li&gt;
&lt;li&gt;Common pitfalls wigh Spring Data JPA pagination and sorting&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;li&gt;
Dynamic Filtering with Spring Data JPA Specifications

&lt;ul&gt;
&lt;li&gt;JpaSpecificationExecutor&lt;/li&gt;
&lt;li&gt;JPA static metamodel&lt;/li&gt;
&lt;li&gt;QueryDSL with Spring Data JPA&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;li&gt;
Spring Data JPA Projections in Kotlin

&lt;ul&gt;
&lt;li&gt;Interface-based projection (read-only view)&lt;/li&gt;
&lt;li&gt;Class/DTO projection with Spring Data JPA&lt;/li&gt;
&lt;li&gt;Dynamic projection (choose shape at call site)&lt;/li&gt;
&lt;li&gt;DTO mapping approaches beyond projections&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;li&gt;At the end&lt;/li&gt;
&lt;/ul&gt;

&lt;h2&gt;
  
  
  Start your Kotlin project with Spring Initializr
&lt;/h2&gt;

&lt;p&gt;For beginners, Spring Initializr is the fastest and safest way to create a correct project skeleton.&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;Open &lt;a href="https://start.spring.io" rel="noopener noreferrer"&gt;start.spring.io&lt;/a&gt;.&lt;/li&gt;
&lt;li&gt;Choose:&lt;/li&gt;
&lt;/ol&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;code&gt;Project&lt;/code&gt;: Gradle (Kotlin)&lt;/li&gt;
&lt;li&gt;
&lt;code&gt;Language&lt;/code&gt;: Kotlin&lt;/li&gt;
&lt;li&gt;
&lt;code&gt;Spring Boot&lt;/code&gt;: latest stable 4.x&lt;/li&gt;
&lt;li&gt;
&lt;code&gt;Group&lt;/code&gt;: for example &lt;code&gt;dev.protsenko&lt;/code&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;code&gt;Artifact&lt;/code&gt;: for example &lt;code&gt;demo&lt;/code&gt;
&lt;/li&gt;
&lt;/ul&gt;

&lt;ol&gt;
&lt;li&gt;Add dependencies:&lt;/li&gt;
&lt;/ol&gt;

&lt;ul&gt;
&lt;li&gt;&lt;code&gt;Spring Web&lt;/code&gt;&lt;/li&gt;
&lt;li&gt;&lt;code&gt;Spring Data JPA&lt;/code&gt;&lt;/li&gt;
&lt;li&gt;one database driver (&lt;code&gt;H2&lt;/code&gt; for local learning, or &lt;code&gt;PostgreSQL Driver&lt;/code&gt; for real DB usage)&lt;/li&gt;
&lt;/ul&gt;

&lt;ol&gt;
&lt;li&gt;Generate and unzip the project.&lt;/li&gt;
&lt;li&gt;Open it in IntelliJ IDEA and run the main application class.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;Recommendation: use Spring Initializr for your first projects and most new services. It prevents common setup mistakes and gives you a clean baseline to start coding features immediately.&lt;/p&gt;

&lt;p&gt;At this point, your project should be running, so let’s move to the core Spring Data JPA concept: entities.&lt;/p&gt;

&lt;h2&gt;
  
  
  JPA Entity Basics in Kotlin: &lt;a class="mentioned-user" href="https://dev.to/entity"&gt;@entity&lt;/a&gt;, &lt;a class="mentioned-user" href="https://dev.to/id"&gt;@id&lt;/a&gt;, &lt;a class="mentioned-user" href="https://dev.to/column"&gt;@column&lt;/a&gt;
&lt;/h2&gt;

&lt;p&gt;A &lt;strong&gt;JPA entity&lt;/strong&gt; is a Kotlin class that JPA maps to a database table. One entity instance usually represents one row. Fields map to columns, and associations (&lt;code&gt;@OneToMany&lt;/code&gt;, &lt;code&gt;@ManyToOne&lt;/code&gt;, etc.) map to relationships.&lt;/p&gt;

&lt;p&gt;At minimum, an entity needs &lt;code&gt;@Entity&lt;/code&gt; and a primary key definition (&lt;code&gt;@Id&lt;/code&gt; or &lt;code&gt;@EmbeddedId&lt;/code&gt;). In practice, JPA annotations split into three layers: class-level mapping (&lt;code&gt;@Entity&lt;/code&gt;), key mapping (&lt;code&gt;@Id&lt;/code&gt; or &lt;code&gt;@EmbeddedId&lt;/code&gt;), and optional field-level tuning (&lt;code&gt;@Column&lt;/code&gt; when defaults are not enough). The next subchapters explain each layer.&lt;/p&gt;

&lt;h3&gt;
  
  
  &lt;code&gt;@Entity&lt;/code&gt;
&lt;/h3&gt;

&lt;ul&gt;
&lt;li&gt;For what: marks a Kotlin class as a JPA entity (persistent model).&lt;/li&gt;
&lt;li&gt;Arguments: main argument is &lt;code&gt;name&lt;/code&gt;, used by JPQL (&lt;code&gt;@Entity(name = "...")&lt;/code&gt;).&lt;/li&gt;
&lt;li&gt;When to use: always on persistent classes; set &lt;code&gt;name&lt;/code&gt; explicitly when you use JPQL strings and want safer class refactors.&lt;/li&gt;
&lt;/ul&gt;

&lt;h3&gt;
  
  
  &lt;code&gt;@Id&lt;/code&gt;
&lt;/h3&gt;

&lt;ul&gt;
&lt;li&gt;For what: defines a single-column primary key.&lt;/li&gt;
&lt;li&gt;Arguments: &lt;code&gt;@Id&lt;/code&gt; itself has no arguments; it is commonly paired with &lt;code&gt;@GeneratedValue(strategy = ...)&lt;/code&gt;.&lt;/li&gt;
&lt;li&gt;When to use: when your table key is one column (for example &lt;code&gt;id&lt;/code&gt; UUID, Long, Integer).&lt;/li&gt;
&lt;/ul&gt;

&lt;h3&gt;
  
  
  &lt;code&gt;@EmbeddedId&lt;/code&gt;
&lt;/h3&gt;

&lt;ul&gt;
&lt;li&gt;For what: defines a composite primary key via an embeddable key object.&lt;/li&gt;
&lt;li&gt;Arguments: &lt;code&gt;@EmbeddedId&lt;/code&gt; has no arguments; key fields are defined in the embeddable class.&lt;/li&gt;
&lt;li&gt;When to use: when the table primary key is naturally multi-column.&lt;/li&gt;
&lt;/ul&gt;

&lt;h3&gt;
  
  
  &lt;code&gt;@Column(...)&lt;/code&gt; (optional)
&lt;/h3&gt;

&lt;ul&gt;
&lt;li&gt;For what: customizes field-to-column mapping.&lt;/li&gt;
&lt;li&gt;Arguments and how they work:&lt;/li&gt;
&lt;li&gt;
&lt;code&gt;name&lt;/code&gt;: explicit DB column name. Use when DB naming differs from your Kotlin property name.&lt;/li&gt;
&lt;li&gt;
&lt;code&gt;nullable&lt;/code&gt;: whether the column can store &lt;code&gt;NULL&lt;/code&gt;. Keep this aligned with Kotlin type nullability. When Hibernate generates DDL it uses this value to emit &lt;code&gt;NOT NULL&lt;/code&gt;; when you manage schema with a migration tool (Liquibase, Flyway), the constraint lives in the migration script – &lt;code&gt;@Column(nullable = false)&lt;/code&gt; still communicates intent to the ORM, but the actual &lt;code&gt;NOT NULL&lt;/code&gt; in the database comes from your migration.&lt;/li&gt;
&lt;li&gt;
&lt;code&gt;length&lt;/code&gt;: max length for string columns (for example &lt;code&gt;VARCHAR&lt;/code&gt;). Use for bounded text fields.&lt;/li&gt;
&lt;li&gt;
&lt;code&gt;unique&lt;/code&gt;: shorthand single-column unique constraint. Use sparingly; prefer DB migrations for complex unique indexes.&lt;/li&gt;
&lt;li&gt;
&lt;code&gt;precision&lt;/code&gt;: total number of digits for decimal columns (usually with &lt;code&gt;BigDecimal&lt;/code&gt;).&lt;/li&gt;
&lt;li&gt;
&lt;code&gt;scale&lt;/code&gt;: number of digits after decimal point (usually with &lt;code&gt;BigDecimal&lt;/code&gt;).&lt;/li&gt;
&lt;li&gt;When to use: when default mapping is not enough. For minimal entities, you can omit &lt;code&gt;@Column&lt;/code&gt;.&lt;/li&gt;
&lt;li&gt;Kotlin nullability rule:&lt;/li&gt;
&lt;li&gt;Prefer non-null Kotlin types by default (&lt;code&gt;String&lt;/code&gt;, &lt;code&gt;Int&lt;/code&gt;, &lt;code&gt;UUID&lt;/code&gt;) for required data.&lt;/li&gt;
&lt;li&gt;Use nullable Kotlin types (&lt;code&gt;String?&lt;/code&gt;, &lt;code&gt;Int?&lt;/code&gt;, &lt;code&gt;UUID?&lt;/code&gt;) only when the value is truly optional in business logic.&lt;/li&gt;
&lt;li&gt;Keep type and column settings consistent: non-null type with &lt;code&gt;nullable = false&lt;/code&gt;, nullable type with &lt;code&gt;nullable = true&lt;/code&gt;.&lt;/li&gt;
&lt;li&gt;Important: a non-null Kotlin type alone does &lt;strong&gt;not&lt;/strong&gt; create a &lt;code&gt;NOT NULL&lt;/code&gt; constraint in the database. Add &lt;code&gt;@Column(nullable = false)&lt;/code&gt; on required fields to communicate nullability intent to the ORM. The actual constraint in the database depends on how you manage schema: Hibernate-generated DDL will use this annotation, but in production environments schema is typically managed by a migration tool (Liquibase, Flyway) – define &lt;code&gt;NOT NULL&lt;/code&gt; in the migration script and keep it in sync with the entity annotation.&lt;/li&gt;
&lt;/ul&gt;

&lt;h3&gt;
  
  
  No-arg constructor requirement
&lt;/h3&gt;

&lt;ul&gt;
&lt;li&gt;For what: JPA needs a no-arg constructor for entity instantiation.&lt;/li&gt;
&lt;li&gt;Arguments: not an annotation itself in this context.&lt;/li&gt;
&lt;li&gt;When to use: always required; in Kotlin projects this is typically handled by the &lt;strong&gt;Kotlin JPA plugin&lt;/strong&gt; (&lt;code&gt;kotlin("plugin.jpa")&lt;/code&gt;), which generates synthetic no-arg constructors for &lt;code&gt;@Entity&lt;/code&gt;-annotated classes at compile time.&lt;/li&gt;
&lt;li&gt;Non-final requirement: Jakarta Persistence also requires entity classes and their persistent members to be non-final. Kotlin classes are final by default, so Kotlin projects add &lt;code&gt;kotlin("plugin.allopen")&lt;/code&gt; (or the Spring Boot equivalent &lt;code&gt;kotlin("plugin.spring")&lt;/code&gt; combined with &lt;code&gt;allOpen&lt;/code&gt; JPA annotation configuration) to make JPA-annotated classes open automatically.&lt;/li&gt;
&lt;/ul&gt;

&lt;h3&gt;
  
  
  Mapping Domain States with Enums
&lt;/h3&gt;

&lt;p&gt;Enums are the safest way to represent different states (status, type, role, mode) in Spring Data JPA.&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;For what: map business states to a closed set of values instead of magic numbers or free-text strings.&lt;/li&gt;
&lt;li&gt;How it works: use &lt;code&gt;@Enumerated(EnumType.STRING)&lt;/code&gt; on the enum field.&lt;/li&gt;
&lt;li&gt;When to use: default choice for state columns. Avoid &lt;code&gt;EnumType.ORDINAL&lt;/code&gt; because reordering enum constants can silently change data meaning.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;If your existing schema stores numeric codes (for example &lt;code&gt;1&lt;/code&gt;, &lt;code&gt;2&lt;/code&gt;, &lt;code&gt;3&lt;/code&gt;), use an &lt;code&gt;AttributeConverter&lt;/code&gt; instead of &lt;code&gt;EnumType.ORDINAL&lt;/code&gt;.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight kotlin"&gt;&lt;code&gt;&lt;span class="nd"&gt;@Converter&lt;/span&gt;
&lt;span class="kd"&gt;class&lt;/span&gt; &lt;span class="nc"&gt;CompanyStatusCodeConverter&lt;/span&gt; &lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="nc"&gt;AttributeConverter&lt;/span&gt;&lt;span class="p"&gt;&amp;lt;&lt;/span&gt;&lt;span class="nc"&gt;CompanyStatus&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="nc"&gt;Int&lt;/span&gt;&lt;span class="p"&gt;&amp;gt;&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
    &lt;span class="k"&gt;override&lt;/span&gt; &lt;span class="k"&gt;fun&lt;/span&gt; &lt;span class="nf"&gt;convertToDatabaseColumn&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;attribute&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="nc"&gt;CompanyStatus&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="p"&gt;=&lt;/span&gt; &lt;span class="k"&gt;when&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;attribute&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
        &lt;span class="nc"&gt;CompanyStatus&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nc"&gt;ACTIVE&lt;/span&gt; &lt;span class="p"&gt;-&amp;gt;&lt;/span&gt; &lt;span class="mi"&gt;1&lt;/span&gt;
        &lt;span class="nc"&gt;CompanyStatus&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nc"&gt;SUSPENDED&lt;/span&gt; &lt;span class="p"&gt;-&amp;gt;&lt;/span&gt; &lt;span class="mi"&gt;2&lt;/span&gt;
        &lt;span class="nc"&gt;CompanyStatus&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nc"&gt;DISSOLVED&lt;/span&gt; &lt;span class="p"&gt;-&amp;gt;&lt;/span&gt; &lt;span class="mi"&gt;3&lt;/span&gt;
    &lt;span class="p"&gt;}&lt;/span&gt;

    &lt;span class="k"&gt;override&lt;/span&gt; &lt;span class="k"&gt;fun&lt;/span&gt; &lt;span class="nf"&gt;convertToEntityAttribute&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;dbData&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="nc"&gt;Int&lt;/span&gt;&lt;span class="p"&gt;?)&lt;/span&gt; &lt;span class="p"&gt;=&lt;/span&gt; &lt;span class="k"&gt;when&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;dbData&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
        &lt;span class="mi"&gt;1&lt;/span&gt; &lt;span class="p"&gt;-&amp;gt;&lt;/span&gt; &lt;span class="nc"&gt;CompanyStatus&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nc"&gt;ACTIVE&lt;/span&gt;
        &lt;span class="mi"&gt;2&lt;/span&gt; &lt;span class="p"&gt;-&amp;gt;&lt;/span&gt; &lt;span class="nc"&gt;CompanyStatus&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nc"&gt;SUSPENDED&lt;/span&gt;
        &lt;span class="mi"&gt;3&lt;/span&gt; &lt;span class="p"&gt;-&amp;gt;&lt;/span&gt; &lt;span class="nc"&gt;CompanyStatus&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nc"&gt;DISSOLVED&lt;/span&gt;
        &lt;span class="k"&gt;else&lt;/span&gt; &lt;span class="p"&gt;-&amp;gt;&lt;/span&gt; &lt;span class="k"&gt;throw&lt;/span&gt; &lt;span class="nc"&gt;IllegalArgumentException&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s"&gt;"Unknown status code: $dbData"&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
    &lt;span class="p"&gt;}&lt;/span&gt;
&lt;span class="p"&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Two rules for writing a safe converter:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;code&gt;convertToDatabaseColumn&lt;/code&gt; receives the Kotlin type – match its nullability to the entity field. If the field is non-nullable (&lt;code&gt;CompanyStatus&lt;/code&gt;), the parameter is non-nullable too – no &lt;code&gt;null&lt;/code&gt; branch needed.&lt;/li&gt;
&lt;li&gt;
&lt;code&gt;convertToEntityAttribute&lt;/code&gt; must never silently return &lt;code&gt;null&lt;/code&gt; for unknown DB values when the entity field is non-nullable. Throw instead – a corrupt database value is a programming error, not a recoverable state.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Use it on the entity field:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight kotlin"&gt;&lt;code&gt;&lt;span class="nd"&gt;@Convert&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;converter&lt;/span&gt; &lt;span class="p"&gt;=&lt;/span&gt; &lt;span class="nc"&gt;CompanyStatusCodeConverter&lt;/span&gt;&lt;span class="o"&gt;::&lt;/span&gt;&lt;span class="k"&gt;class&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
&lt;span class="kd"&gt;var&lt;/span&gt; &lt;span class="py"&gt;status&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="nc"&gt;CompanyStatus&lt;/span&gt; &lt;span class="p"&gt;=&lt;/span&gt; &lt;span class="nc"&gt;CompanyStatus&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nc"&gt;ACTIVE&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Example: let’s map a &lt;code&gt;company&lt;/code&gt; table to an entity with &lt;code&gt;id&lt;/code&gt; (UUID primary key), &lt;code&gt;name&lt;/code&gt;, &lt;code&gt;countryCode&lt;/code&gt;, &lt;code&gt;status&lt;/code&gt; (enum), and optional &lt;code&gt;description&lt;/code&gt;.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight kotlin"&gt;&lt;code&gt;&lt;span class="k"&gt;enum&lt;/span&gt; &lt;span class="kd"&gt;class&lt;/span&gt; &lt;span class="nc"&gt;CompanyStatus&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
    &lt;span class="nc"&gt;ACTIVE&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
    &lt;span class="nc"&gt;SUSPENDED&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
    &lt;span class="nc"&gt;DISSOLVED&lt;/span&gt;
&lt;span class="p"&gt;}&lt;/span&gt;

&lt;span class="nd"&gt;@Entity&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;name&lt;/span&gt; &lt;span class="p"&gt;=&lt;/span&gt; &lt;span class="s"&gt;"Company"&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
&lt;span class="nd"&gt;@Table&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;name&lt;/span&gt; &lt;span class="p"&gt;=&lt;/span&gt; &lt;span class="s"&gt;"company"&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
&lt;span class="kd"&gt;class&lt;/span&gt; &lt;span class="nc"&gt;Company&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;
    &lt;span class="kd"&gt;val&lt;/span&gt; &lt;span class="py"&gt;name&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="nc"&gt;String&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
    &lt;span class="kd"&gt;val&lt;/span&gt; &lt;span class="py"&gt;countryCode&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="nc"&gt;String&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
    &lt;span class="nd"&gt;@Enumerated&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nc"&gt;EnumType&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nc"&gt;STRING&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
    &lt;span class="kd"&gt;var&lt;/span&gt; &lt;span class="py"&gt;status&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="nc"&gt;CompanyStatus&lt;/span&gt; &lt;span class="p"&gt;=&lt;/span&gt; &lt;span class="nc"&gt;CompanyStatus&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nc"&gt;ACTIVE&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
    &lt;span class="kd"&gt;var&lt;/span&gt; &lt;span class="py"&gt;description&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="nc"&gt;String&lt;/span&gt;&lt;span class="p"&gt;?&lt;/span&gt; &lt;span class="p"&gt;=&lt;/span&gt; &lt;span class="k"&gt;null&lt;/span&gt;
&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
    &lt;span class="nd"&gt;@Id&lt;/span&gt;
    &lt;span class="nd"&gt;@GeneratedValue&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;strategy&lt;/span&gt; &lt;span class="p"&gt;=&lt;/span&gt; &lt;span class="nc"&gt;GenerationType&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nc"&gt;UUID&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
    &lt;span class="kd"&gt;var&lt;/span&gt; &lt;span class="py"&gt;id&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="nc"&gt;UUID&lt;/span&gt;&lt;span class="p"&gt;?&lt;/span&gt; &lt;span class="p"&gt;=&lt;/span&gt; &lt;span class="k"&gt;null&lt;/span&gt;
&lt;span class="p"&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h3&gt;
  
  
  Overriding equals and hashCode in JPA Entities
&lt;/h3&gt;

&lt;p&gt;Overriding &lt;code&gt;equals&lt;/code&gt; and &lt;code&gt;hashCode&lt;/code&gt; in JPA entities is context-dependent. Many applications work fine with defaults from &lt;code&gt;Any&lt;/code&gt;/&lt;code&gt;Object&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;Context details:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;In a typical Spring Boot &lt;code&gt;spring-boot-starter-data-jpa&lt;/code&gt; setup, Hibernate is the JPA provider (ORM library) brought in by the starter.&lt;/li&gt;
&lt;li&gt;A &lt;strong&gt;persistence context&lt;/strong&gt; is Hibernate’s first-level cache bound to the current transaction/session. Inside that scope, one DB row is represented by one managed object instance.&lt;/li&gt;
&lt;li&gt;Because of that identity map, reference equality is often enough while you stay in one transaction/session.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Why dynamic/mutable &lt;code&gt;equals&lt;/code&gt;/&lt;code&gt;hashCode&lt;/code&gt; is dangerous:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;If equality depends on mutable fields, object hash can change after insertion into &lt;code&gt;Set&lt;/code&gt;/&lt;code&gt;Map&lt;/code&gt;, which breaks lookup/remove behavior.&lt;/li&gt;
&lt;li&gt;If equality touches lazy associations, &lt;code&gt;equals&lt;/code&gt;/&lt;code&gt;hashCode&lt;/code&gt;/&lt;code&gt;toString&lt;/code&gt; can trigger extra SQL queries unexpectedly (N+1 side effects).&lt;/li&gt;
&lt;li&gt;If equality traverses relationships, it can recurse deeply, increase CPU/memory usage, and even cause stack overflows in cyclic graphs.&lt;/li&gt;
&lt;li&gt;In practice, these patterns create correctness bugs first, and performance problems second.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Custom equality is usually needed only when:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;entities are keys in &lt;code&gt;Map&lt;/code&gt;,&lt;/li&gt;
&lt;li&gt;entities are stored in &lt;code&gt;Set&lt;/code&gt;,&lt;/li&gt;
&lt;li&gt;entities are compared across persistence contexts.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Main strategies:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;strong&gt;Default implementation from &lt;code&gt;Any&lt;/code&gt;/&lt;code&gt;Object&lt;/code&gt; (recommended baseline).&lt;/strong&gt; This is reference-based equality, which works well when entities stay inside one persistence context and are not used as keys in hashed collections.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Business-key equality&lt;/strong&gt; (recommended only if the key is unique and immutable).&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;ID-based equality&lt;/strong&gt; (common with generated IDs, but requires careful handling of transient entities with &lt;code&gt;id == null&lt;/code&gt;).&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;All-fields equality&lt;/strong&gt; is unsafe for JPA entities (mutable fields, lazy associations, recursion risk, and unstable hashes).&lt;/li&gt;
&lt;/ul&gt;

&lt;h3&gt;
  
  
  Best Practices for Designing JPA Entities
&lt;/h3&gt;

&lt;p&gt;Field typing practices for entities:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Match Kotlin nullability to DB nullability: &lt;code&gt;String&lt;/code&gt; for required values, &lt;code&gt;String?&lt;/code&gt; only for truly optional data. Annotate required fields with &lt;code&gt;@Column(nullable = false)&lt;/code&gt; to communicate nullability intent to the ORM. In production, the actual &lt;code&gt;NOT NULL&lt;/code&gt; constraint is typically defined in a migration tool (Liquibase, Flyway) – keep the entity annotation and migration script in sync.&lt;/li&gt;
&lt;li&gt;Prefer domain-safe types over primitives where meaning matters: &lt;code&gt;BigDecimal&lt;/code&gt; for money, &lt;code&gt;Instant&lt;/code&gt;/&lt;code&gt;OffsetDateTime&lt;/code&gt; for timestamps, enums for finite states.&lt;/li&gt;
&lt;li&gt;Reuse embeddable value objects (&lt;code&gt;@Embeddable&lt;/code&gt;) for repeated concepts (for example, address, amount+currency) instead of duplicating scalar fields across entities.&lt;/li&gt;
&lt;li&gt;Avoid fake placeholder values (empty string, &lt;code&gt;0&lt;/code&gt;, &lt;code&gt;-1&lt;/code&gt;) for “missing” data. When a value is truly optional, represent it explicitly as a nullable DB column + nullable Kotlin type (&lt;code&gt;String?&lt;/code&gt;, &lt;code&gt;Int?&lt;/code&gt;) or model it as an enum state like &lt;code&gt;UNKNOWN&lt;/code&gt;/&lt;code&gt;NOT_PROVIDED&lt;/code&gt;.&lt;/li&gt;
&lt;li&gt;Avoid putting heavy business logic in entity constructors; keep constructor requirements minimal for ORM lifecycle.&lt;/li&gt;
&lt;li&gt;Avoid &lt;code&gt;data class&lt;/code&gt; for entities because generated &lt;code&gt;equals&lt;/code&gt;/&lt;code&gt;hashCode&lt;/code&gt;/&lt;code&gt;toString&lt;/code&gt;/&lt;code&gt;copy&lt;/code&gt; conflict with JPA lifecycle and lazy associations.&lt;/li&gt;
&lt;/ul&gt;

&lt;h3&gt;
  
  
  Can a Kotlin data class be a JPA entity?
&lt;/h3&gt;

&lt;p&gt;It compiles, and Hibernate will even save it. That’s the trap. A Kotlin &lt;code&gt;data class&lt;/code&gt; generates &lt;code&gt;equals&lt;/code&gt;, &lt;code&gt;hashCode&lt;/code&gt;, &lt;code&gt;toString&lt;/code&gt; and &lt;code&gt;copy&lt;/code&gt; from every property in the primary constructor, and on an entity those properties include the generated id and the associations.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight kotlin"&gt;&lt;code&gt;&lt;span class="nd"&gt;@Entity&lt;/span&gt;
&lt;span class="kd"&gt;data class&lt;/span&gt; &lt;span class="nc"&gt;Author&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;
    &lt;span class="nd"&gt;@Id&lt;/span&gt;
    &lt;span class="nd"&gt;@GeneratedValue&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;strategy&lt;/span&gt; &lt;span class="p"&gt;=&lt;/span&gt; &lt;span class="nc"&gt;GenerationType&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nc"&gt;UUID&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
    &lt;span class="kd"&gt;var&lt;/span&gt; &lt;span class="py"&gt;id&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="nc"&gt;UUID&lt;/span&gt;&lt;span class="p"&gt;?&lt;/span&gt; &lt;span class="p"&gt;=&lt;/span&gt; &lt;span class="k"&gt;null&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
    &lt;span class="kd"&gt;var&lt;/span&gt; &lt;span class="py"&gt;name&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="nc"&gt;String&lt;/span&gt; &lt;span class="p"&gt;=&lt;/span&gt; &lt;span class="s"&gt;""&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
    &lt;span class="nd"&gt;@OneToMany&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;mappedBy&lt;/span&gt; &lt;span class="p"&gt;=&lt;/span&gt; &lt;span class="s"&gt;"author"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;cascade&lt;/span&gt; &lt;span class="p"&gt;=&lt;/span&gt; &lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="nc"&gt;CascadeType&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nc"&gt;ALL&lt;/span&gt;&lt;span class="p"&gt;])&lt;/span&gt;
    &lt;span class="kd"&gt;val&lt;/span&gt; &lt;span class="py"&gt;books&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="nc"&gt;MutableList&lt;/span&gt;&lt;span class="p"&gt;&amp;lt;&lt;/span&gt;&lt;span class="nc"&gt;Book&lt;/span&gt;&lt;span class="p"&gt;&amp;gt;&lt;/span&gt; &lt;span class="p"&gt;=&lt;/span&gt; &lt;span class="nf"&gt;mutableListOf&lt;/span&gt;&lt;span class="p"&gt;(),&lt;/span&gt;
&lt;span class="p"&gt;)&lt;/span&gt;

&lt;span class="nd"&gt;@Entity&lt;/span&gt;
&lt;span class="kd"&gt;data class&lt;/span&gt; &lt;span class="nc"&gt;Book&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;
    &lt;span class="nd"&gt;@Id&lt;/span&gt;
    &lt;span class="nd"&gt;@GeneratedValue&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;strategy&lt;/span&gt; &lt;span class="p"&gt;=&lt;/span&gt; &lt;span class="nc"&gt;GenerationType&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nc"&gt;UUID&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
    &lt;span class="kd"&gt;var&lt;/span&gt; &lt;span class="py"&gt;id&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="nc"&gt;UUID&lt;/span&gt;&lt;span class="p"&gt;?&lt;/span&gt; &lt;span class="p"&gt;=&lt;/span&gt; &lt;span class="k"&gt;null&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
    &lt;span class="kd"&gt;var&lt;/span&gt; &lt;span class="py"&gt;title&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="nc"&gt;String&lt;/span&gt; &lt;span class="p"&gt;=&lt;/span&gt; &lt;span class="s"&gt;""&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
    &lt;span class="nd"&gt;@ManyToOne&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;fetch&lt;/span&gt; &lt;span class="p"&gt;=&lt;/span&gt; &lt;span class="nc"&gt;FetchType&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nc"&gt;LAZY&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
    &lt;span class="kd"&gt;var&lt;/span&gt; &lt;span class="py"&gt;author&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="nc"&gt;Author&lt;/span&gt;&lt;span class="p"&gt;?&lt;/span&gt; &lt;span class="p"&gt;=&lt;/span&gt; &lt;span class="k"&gt;null&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
&lt;span class="p"&gt;)&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;I reproduced each of these problems with a test against a real Hibernate session:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;
&lt;strong&gt;The entity disappears from a &lt;code&gt;HashSet&lt;/code&gt;.&lt;/strong&gt; Put a new &lt;code&gt;Book&lt;/code&gt; into a set, persist it, and Hibernate fills in &lt;code&gt;id&lt;/code&gt;. The hash code changes with it, so &lt;code&gt;set.contains(book)&lt;/code&gt; returns &lt;code&gt;false&lt;/code&gt; for the same object.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;&lt;code&gt;hashCode&lt;/code&gt; never ends.&lt;/strong&gt; &lt;code&gt;Author.hashCode()&lt;/code&gt; hashes &lt;code&gt;books&lt;/code&gt;, each &lt;code&gt;Book&lt;/code&gt; hashes its &lt;code&gt;author&lt;/code&gt;, and around it goes until &lt;code&gt;StackOverflowError&lt;/code&gt;. &lt;code&gt;toString&lt;/code&gt; and &lt;code&gt;equals&lt;/code&gt; have the same loop on any bidirectional association.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;&lt;code&gt;toString&lt;/code&gt; touches lazy data.&lt;/strong&gt; The generated &lt;code&gt;toString&lt;/code&gt; reads &lt;code&gt;author&lt;/code&gt;, which is a lazy proxy. Call it after the session is closed (a log line after the service returned) and it throws &lt;code&gt;LazyInitializationException&lt;/code&gt;.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;&lt;code&gt;copy()&lt;/code&gt; looks like the entity, but it isn’t managed.&lt;/strong&gt; The copy is &lt;code&gt;equal&lt;/code&gt; to the managed &lt;code&gt;Book&lt;/code&gt;, same id and all, yet Hibernate doesn’t track it. Change its title inside the transaction and the change is never saved.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;Use a regular &lt;code&gt;class&lt;/code&gt; for entities, keep the id out of the constructor, and write &lt;code&gt;toString&lt;/code&gt; by hand without associations:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight kotlin"&gt;&lt;code&gt;&lt;span class="nd"&gt;@Entity&lt;/span&gt;
&lt;span class="kd"&gt;class&lt;/span&gt; &lt;span class="nc"&gt;Book&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;
    &lt;span class="kd"&gt;var&lt;/span&gt; &lt;span class="py"&gt;title&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="nc"&gt;String&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
    &lt;span class="nd"&gt;@ManyToOne&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;fetch&lt;/span&gt; &lt;span class="p"&gt;=&lt;/span&gt; &lt;span class="nc"&gt;FetchType&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nc"&gt;LAZY&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
    &lt;span class="kd"&gt;var&lt;/span&gt; &lt;span class="py"&gt;author&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="nc"&gt;Author&lt;/span&gt;&lt;span class="p"&gt;?&lt;/span&gt; &lt;span class="p"&gt;=&lt;/span&gt; &lt;span class="k"&gt;null&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
    &lt;span class="nd"&gt;@Id&lt;/span&gt;
    &lt;span class="nd"&gt;@GeneratedValue&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;strategy&lt;/span&gt; &lt;span class="p"&gt;=&lt;/span&gt; &lt;span class="nc"&gt;GenerationType&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nc"&gt;UUID&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
    &lt;span class="kd"&gt;var&lt;/span&gt; &lt;span class="py"&gt;id&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="nc"&gt;UUID&lt;/span&gt;&lt;span class="p"&gt;?&lt;/span&gt; &lt;span class="p"&gt;=&lt;/span&gt; &lt;span class="k"&gt;null&lt;/span&gt;

    &lt;span class="k"&gt;override&lt;/span&gt; &lt;span class="k"&gt;fun&lt;/span&gt; &lt;span class="nf"&gt;toString&lt;/span&gt;&lt;span class="p"&gt;()&lt;/span&gt; &lt;span class="p"&gt;=&lt;/span&gt; &lt;span class="s"&gt;"Book(id=$id, title=$title)"&lt;/span&gt;
&lt;span class="p"&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Data classes are still the right tool one layer up: DTOs and class-based projections (see the projection chapter below), where value equality is what you want.&lt;/p&gt;

&lt;p&gt;What a data class compiles to, and where it breaks JPA, Jackson and validation in Spring Boot 4, is in &lt;a href="https://protsenko.dev/kotlin-data-class-spring-boot/" rel="noopener noreferrer"&gt;Kotlin data class in Spring Boot 4: what the bytecode shows&lt;/a&gt;.&lt;/p&gt;

&lt;h2&gt;
  
  
  Accessing Data with JpaRepository and CrudRepository
&lt;/h2&gt;

&lt;p&gt;To access the data you write only a repository &lt;strong&gt;interface&lt;/strong&gt;, and Spring Data JPA creates the real implementation class automatically when the app starts. So the parent interface you choose (&lt;code&gt;CrudRepository&lt;/code&gt;, &lt;code&gt;JpaRepository&lt;/code&gt;, etc.) directly decides what methods your repository has.&lt;/p&gt;

&lt;p&gt;Typical flow:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;Define &lt;code&gt;CompanyRepository&lt;/code&gt; interface.&lt;/li&gt;
&lt;li&gt;Inject it into a service.&lt;/li&gt;
&lt;li&gt;Call methods like &lt;code&gt;save&lt;/code&gt;, &lt;code&gt;findById&lt;/code&gt;, or custom query methods.&lt;/li&gt;
&lt;/ol&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;code&gt;Repository&amp;lt;T, ID&amp;gt;&lt;/code&gt;: marker-only base; you expose only methods you declare.&lt;/li&gt;
&lt;li&gt;
&lt;code&gt;CrudRepository&amp;lt;T, ID&amp;gt;&lt;/code&gt;: adds standard CRUD methods.&lt;/li&gt;
&lt;li&gt;
&lt;code&gt;ListCrudRepository&amp;lt;T, ID&amp;gt;&lt;/code&gt;: same as &lt;code&gt;CrudRepository&lt;/code&gt;, but list-returning methods use &lt;code&gt;List&lt;/code&gt;.&lt;/li&gt;
&lt;li&gt;
&lt;code&gt;PagingAndSortingRepository&amp;lt;T, ID&amp;gt;&lt;/code&gt;: adds pagination and sorting.&lt;/li&gt;
&lt;li&gt;
&lt;code&gt;JpaRepository&amp;lt;T, ID&amp;gt;&lt;/code&gt;: most common default; includes CRUD + pagination + sorting + JPA-specific helpers (&lt;code&gt;flush&lt;/code&gt;, batch operations).&lt;/li&gt;
&lt;li&gt;
&lt;code&gt;JpaSpecificationExecutor&amp;lt;T&amp;gt;&lt;/code&gt; (optional companion interface): dynamic predicate queries via Specifications.&lt;/li&gt;
&lt;li&gt;
&lt;code&gt;QueryByExampleExecutor&amp;lt;T&amp;gt;&lt;/code&gt; (optional companion interface): probe-based querying without explicit JPQL.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Typical Kotlin repository:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight java"&gt;&lt;code&gt;&lt;span class="kd"&gt;interface&lt;/span&gt; &lt;span class="nc"&gt;CompanyRepository&lt;/span&gt; &lt;span class="o"&gt;:&lt;/span&gt; &lt;span class="nc"&gt;JpaRepository&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="nc"&gt;Company&lt;/span&gt;&lt;span class="o"&gt;,&lt;/span&gt; &lt;span class="no"&gt;UUID&lt;/span&gt;&lt;span class="o"&gt;&amp;gt;&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;When to choose what:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;If you need strict API boundaries, extend &lt;code&gt;Repository&lt;/code&gt; (or a slim shared base) and expose only allowed operations. You can also use &lt;code&gt;@NoRepositoryBean&lt;/code&gt; on abstract base repository interfaces.&lt;/li&gt;
&lt;li&gt;If you need a convenient full-CRUD repository, extend &lt;code&gt;JpaRepository&lt;/code&gt;.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Small note: &lt;code&gt;@Repository&lt;/code&gt; is not required on Spring Data repository interfaces. When an interface extends Spring Data repository contracts (&lt;code&gt;Repository&lt;/code&gt;, &lt;code&gt;CrudRepository&lt;/code&gt;, &lt;code&gt;JpaRepository&lt;/code&gt;, etc.), Spring auto-detects it and registers a proxy bean automatically.&lt;/p&gt;

&lt;h3&gt;
  
  
  JPQL and @Query: Querying Data with Spring Data JPA
&lt;/h3&gt;

&lt;p&gt;If you need data access beyond default CRUD methods, Spring Data JPA provides three mainstream query styles:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;
&lt;strong&gt;Derived query methods&lt;/strong&gt; (query generated from method name).&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;JPQL queries&lt;/strong&gt; via &lt;code&gt;@Query&lt;/code&gt;.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Native SQL queries&lt;/strong&gt; via &lt;code&gt;@Query(nativeQuery = true)&lt;/code&gt; or &lt;code&gt;@NativeQuery&lt;/code&gt; (introduced in newer Spring Data versions).&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;What “derived” means:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Spring parses method names like &lt;code&gt;findByCountryCodeAndStatus&lt;/code&gt; and builds JPQL automatically.&lt;/li&gt;
&lt;li&gt;This is best for straightforward filters and keeps repository code concise.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Derived method example with &lt;code&gt;Company&lt;/code&gt;:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight kotlin"&gt;&lt;code&gt;&lt;span class="k"&gt;fun&lt;/span&gt; &lt;span class="nf"&gt;findByCountryCodeAndStatus&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;countryCode&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="nc"&gt;String&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;status&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="nc"&gt;CompanyStatus&lt;/span&gt;&lt;span class="p"&gt;):&lt;/span&gt; &lt;span class="nc"&gt;List&lt;/span&gt;&lt;span class="p"&gt;&amp;lt;&lt;/span&gt;&lt;span class="nc"&gt;Company&lt;/span&gt;&lt;span class="p"&gt;&amp;gt;&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Explicit JPQL query with &lt;code&gt;Company&lt;/code&gt;:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight kotlin"&gt;&lt;code&gt;&lt;span class="nd"&gt;@Query&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;
    &lt;span class="s"&gt;"select c from Company c where c.countryCode = :countryCode and c.status = :status"&lt;/span&gt;
&lt;span class="p"&gt;)&lt;/span&gt;
&lt;span class="k"&gt;fun&lt;/span&gt; &lt;span class="nf"&gt;findActiveInCountry&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;
    &lt;span class="nd"&gt;@Param&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s"&gt;"countryCode"&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="n"&gt;countryCode&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="nc"&gt;String&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
    &lt;span class="nd"&gt;@Param&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s"&gt;"status"&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="n"&gt;status&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="nc"&gt;CompanyStatus&lt;/span&gt;
&lt;span class="p"&gt;):&lt;/span&gt; &lt;span class="nc"&gt;List&lt;/span&gt;&lt;span class="p"&gt;&amp;lt;&lt;/span&gt;&lt;span class="nc"&gt;Company&lt;/span&gt;&lt;span class="p"&gt;&amp;gt;&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h3&gt;
  
  
  Updating data in repositories
&lt;/h3&gt;

&lt;p&gt;For update/delete JPQL queries, both annotations are important:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;code&gt;@Modifying&lt;/code&gt; tells Spring Data this query changes data (not a select).&lt;/li&gt;
&lt;li&gt;
&lt;code&gt;@Transactional&lt;/code&gt; provides transaction boundaries so the change is committed atomically.
&lt;/li&gt;
&lt;/ul&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight kotlin"&gt;&lt;code&gt;&lt;span class="nd"&gt;@Modifying&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;clearAutomatically&lt;/span&gt; &lt;span class="p"&gt;=&lt;/span&gt; &lt;span class="k"&gt;true&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;flushAutomatically&lt;/span&gt; &lt;span class="p"&gt;=&lt;/span&gt; &lt;span class="k"&gt;true&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
&lt;span class="nd"&gt;@Transactional&lt;/span&gt;
&lt;span class="nd"&gt;@Query&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s"&gt;"update Company c set c.status = :status where c.id = :id"&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
&lt;span class="k"&gt;fun&lt;/span&gt; &lt;span class="nf"&gt;updateStatus&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;
    &lt;span class="nd"&gt;@Param&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s"&gt;"id"&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="n"&gt;id&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="nc"&gt;UUID&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
    &lt;span class="nd"&gt;@Param&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s"&gt;"status"&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="n"&gt;status&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="nc"&gt;CompanyStatus&lt;/span&gt;
&lt;span class="p"&gt;):&lt;/span&gt; &lt;span class="nc"&gt;Int&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Bulk JPQL &lt;code&gt;update&lt;/code&gt;/&lt;code&gt;delete&lt;/code&gt; queries run directly in the database and bypass the normal entity lifecycle in the current persistence context. In practice, this means managed entities that were already loaded (for example, a &lt;code&gt;Company&lt;/code&gt; fetched earlier in the same transaction) are not automatically synchronized with the bulk result, so your code can keep reading stale in-memory values. That stale state can cause incorrect business decisions, confusing test behavior, and accidental overwrite patterns later in the same transaction. The safe default is to flush pending changes before the bulk query and clear the persistence context after it; in Spring Data JPA, &lt;code&gt;@Modifying(clearAutomatically = true, flushAutomatically = true)&lt;/code&gt; is a practical way to enforce that for repository bulk methods.&lt;/p&gt;

&lt;h3&gt;
  
  
  Kotlin-Idiomatic Entity Fetching with Spring Data JPA
&lt;/h3&gt;

&lt;p&gt;Spring Data’s Java APIs commonly use &lt;code&gt;Optional&amp;lt;T&amp;gt;&lt;/code&gt; for missing individual CRUD results, while query methods can also model absence through &lt;code&gt;null&lt;/code&gt; or wrapper return types. In Kotlin, &lt;code&gt;Optional&amp;lt;T&amp;gt;&lt;/code&gt; is unnecessary: the type system already expresses presence and absence through nullable types (&lt;code&gt;T&lt;/code&gt; vs &lt;code&gt;T?&lt;/code&gt;). Spring Data provides native ways to work with this directly.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight kotlin"&gt;&lt;code&gt;&lt;span class="c1"&gt;// You could specify nullable values in repositories&lt;/span&gt;
&lt;span class="k"&gt;fun&lt;/span&gt; &lt;span class="nf"&gt;findByName&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;name&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="nc"&gt;String&lt;/span&gt;&lt;span class="p"&gt;):&lt;/span&gt; &lt;span class="nc"&gt;Company&lt;/span&gt;&lt;span class="p"&gt;?&lt;/span&gt;
&lt;span class="nd"&gt;@Query&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s"&gt;"select c from Company c where c.name = :name"&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
&lt;span class="k"&gt;fun&lt;/span&gt; &lt;span class="nf"&gt;findOneByName&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nd"&gt;@Param&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s"&gt;"name"&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="n"&gt;name&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="nc"&gt;String&lt;/span&gt;&lt;span class="p"&gt;):&lt;/span&gt; &lt;span class="nc"&gt;Company&lt;/span&gt;&lt;span class="p"&gt;?&lt;/span&gt;

&lt;span class="c1"&gt;// Remember: non-nullable return values will raise exception in runtime&lt;/span&gt;
&lt;span class="k"&gt;fun&lt;/span&gt; &lt;span class="nf"&gt;getByName&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;name&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="nc"&gt;String&lt;/span&gt;&lt;span class="p"&gt;):&lt;/span&gt; &lt;span class="nc"&gt;Company&lt;/span&gt;
&lt;span class="nd"&gt;@Query&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s"&gt;"select c from Company c where c.name = :name"&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
&lt;span class="k"&gt;fun&lt;/span&gt; &lt;span class="nf"&gt;getOneByName&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nd"&gt;@Param&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s"&gt;"name"&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="n"&gt;name&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="nc"&gt;String&lt;/span&gt;&lt;span class="p"&gt;):&lt;/span&gt; &lt;span class="nc"&gt;Company&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Prefer nullable return types (&lt;code&gt;Company?&lt;/code&gt;) as the default. A non-nullable return type (&lt;code&gt;Company&lt;/code&gt;) throws &lt;code&gt;EmptyResultDataAccessException&lt;/code&gt; at runtime when no result is found – this is a runtime error the compiler cannot warn you about, making it easy to miss.&lt;/p&gt;

&lt;p&gt;Another idiomatic option is &lt;code&gt;findByIdOrNull&lt;/code&gt;, a Spring Data extension function that returns &lt;code&gt;T?&lt;/code&gt; directly:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight kotlin"&gt;&lt;code&gt;&lt;span class="kd"&gt;val&lt;/span&gt; &lt;span class="py"&gt;company&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="nc"&gt;Company&lt;/span&gt;&lt;span class="p"&gt;?&lt;/span&gt; &lt;span class="p"&gt;=&lt;/span&gt; &lt;span class="n"&gt;companyRepository&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;findByIdOrNull&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;id&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The import is required – &lt;code&gt;findByIdOrNull&lt;/code&gt; is a top-level extension function on &lt;code&gt;CrudRepository&lt;/code&gt; and will not resolve without it.&lt;/p&gt;

&lt;h2&gt;
  
  
  Pagination in Spring Boot: Pageable, Page, and Slice
&lt;/h2&gt;

&lt;p&gt;Most applications need to return data in pages rather than all at once. Spring Data JPA provides three result types for paginated queries – choose based on what the caller actually needs.&lt;/p&gt;

&lt;h3&gt;
  
  
  Page vs Slice vs List
&lt;/h3&gt;

&lt;div class="table-wrapper-paragraph"&gt;&lt;table&gt;
&lt;thead&gt;
&lt;tr&gt;
&lt;th&gt;&lt;/th&gt;
&lt;th&gt;&lt;code&gt;Page&amp;lt;T&amp;gt;&lt;/code&gt;&lt;/th&gt;
&lt;th&gt;&lt;code&gt;Slice&amp;lt;T&amp;gt;&lt;/code&gt;&lt;/th&gt;
&lt;th&gt;&lt;code&gt;List&amp;lt;T&amp;gt;&lt;/code&gt;&lt;/th&gt;
&lt;/tr&gt;
&lt;/thead&gt;
&lt;tbody&gt;
&lt;tr&gt;
&lt;td&gt;COUNT query&lt;/td&gt;
&lt;td&gt;Yes&lt;/td&gt;
&lt;td&gt;No&lt;/td&gt;
&lt;td&gt;No&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;Knows total records&lt;/td&gt;
&lt;td&gt;Yes&lt;/td&gt;
&lt;td&gt;No&lt;/td&gt;
&lt;td&gt;No&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;
&lt;code&gt;hasNext()&lt;/code&gt; mechanism&lt;/td&gt;
&lt;td&gt;&lt;code&gt;number + 1 &amp;lt; totalPages&lt;/code&gt;&lt;/td&gt;
&lt;td&gt;fetches N+1 rows&lt;/td&gt;
&lt;td&gt;n/a&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;Use case&lt;/td&gt;
&lt;td&gt;UI with page numbers, total count in API&lt;/td&gt;
&lt;td&gt;infinite scroll, “load more”&lt;/td&gt;
&lt;td&gt;all results, caller controls&lt;/td&gt;
&lt;/tr&gt;
&lt;/tbody&gt;
&lt;/table&gt;&lt;/div&gt;

&lt;p&gt;&lt;strong&gt;&lt;code&gt;Page&amp;lt;T&amp;gt;&lt;/code&gt;&lt;/strong&gt; fires a &lt;code&gt;SELECT count(*)&lt;/code&gt; query when necessary so the caller knows the total number of records. Use it when you need to render “Page 3 of 47” or expose &lt;code&gt;totalElements&lt;/code&gt; in an API response.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;&lt;code&gt;Slice&amp;lt;T&amp;gt;&lt;/code&gt;&lt;/strong&gt; skips the count query entirely. Spring Data fetches &lt;code&gt;pageSize + 1&lt;/code&gt; rows – if more than &lt;code&gt;pageSize&lt;/code&gt; rows come back, &lt;code&gt;hasNext()&lt;/code&gt; returns &lt;code&gt;true&lt;/code&gt; and the extra row is discarded. Use it for infinite scroll or “load more” UIs where the total is irrelevant.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;&lt;code&gt;List&amp;lt;T&amp;gt;&lt;/code&gt; with &lt;code&gt;Pageable&lt;/code&gt;&lt;/strong&gt; returns only the content with no metadata at all. Use it when you need a window of results but don’t need navigation information.&lt;/p&gt;

&lt;h3&gt;
  
  
  Pageable and PageRequest
&lt;/h3&gt;

&lt;p&gt;&lt;code&gt;Pageable&lt;/code&gt; is the abstraction that carries which page to retrieve and how to sort it. For paged requests, construct it via &lt;code&gt;PageRequest&lt;/code&gt;:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight kotlin"&gt;&lt;code&gt;&lt;span class="c1"&gt;// Page 0, 20 items per page, no sort&lt;/span&gt;
&lt;span class="kd"&gt;val&lt;/span&gt; &lt;span class="py"&gt;page&lt;/span&gt; &lt;span class="p"&gt;=&lt;/span&gt; &lt;span class="nc"&gt;PageRequest&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;of&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;0&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="mi"&gt;20&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;

&lt;span class="c1"&gt;// With sort&lt;/span&gt;
&lt;span class="kd"&gt;val&lt;/span&gt; &lt;span class="py"&gt;sorted&lt;/span&gt; &lt;span class="p"&gt;=&lt;/span&gt; &lt;span class="nc"&gt;PageRequest&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;of&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;0&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="mi"&gt;20&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="nc"&gt;Sort&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="k"&gt;by&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s"&gt;"name"&lt;/span&gt;&lt;span class="p"&gt;))&lt;/span&gt;
&lt;span class="kd"&gt;val&lt;/span&gt; &lt;span class="py"&gt;desc&lt;/span&gt;   &lt;span class="p"&gt;=&lt;/span&gt; &lt;span class="nc"&gt;PageRequest&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;of&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;0&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="mi"&gt;20&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="nc"&gt;Sort&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nc"&gt;Direction&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nc"&gt;DESC&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="s"&gt;"status"&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;

&lt;span class="c1"&gt;// Shortcut for page 0&lt;/span&gt;
&lt;span class="kd"&gt;val&lt;/span&gt; &lt;span class="py"&gt;first10&lt;/span&gt; &lt;span class="p"&gt;=&lt;/span&gt; &lt;span class="nc"&gt;PageRequest&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;ofSize&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;10&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Page numbers are &lt;strong&gt;zero-based&lt;/strong&gt;: page 0 is the first page.&lt;/p&gt;

&lt;p&gt;&lt;code&gt;PageRequest&lt;/code&gt; is immutable. Use the wither methods to derive a new instance:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight scala"&gt;&lt;code&gt;&lt;span class="k"&gt;val&lt;/span&gt; &lt;span class="nv"&gt;next&lt;/span&gt;     &lt;span class="k"&gt;=&lt;/span&gt; &lt;span class="nv"&gt;page&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="py"&gt;next&lt;/span&gt;&lt;span class="o"&gt;()&lt;/span&gt;               &lt;span class="c1"&gt;// page=1, same size and sort&lt;/span&gt;
&lt;span class="k"&gt;val&lt;/span&gt; &lt;span class="nv"&gt;specific&lt;/span&gt; &lt;span class="k"&gt;=&lt;/span&gt; &lt;span class="nv"&gt;page&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="py"&gt;withPage&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;5&lt;/span&gt;&lt;span class="o"&gt;)&lt;/span&gt;          &lt;span class="c1"&gt;// page=5, same size and sort&lt;/span&gt;
&lt;span class="k"&gt;val&lt;/span&gt; &lt;span class="nv"&gt;resort&lt;/span&gt;   &lt;span class="k"&gt;=&lt;/span&gt; &lt;span class="nv"&gt;page&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="py"&gt;withSort&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="nv"&gt;Sort&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="py"&gt;by&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="s"&gt;"status"&lt;/span&gt;&lt;span class="o"&gt;))&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;To fetch all records without pagination, use &lt;code&gt;Pageable.unpaged()&lt;/code&gt;. A repository method that accepts &lt;code&gt;Pageable&lt;/code&gt; and returns &lt;code&gt;Page&amp;lt;T&amp;gt;&lt;/code&gt; will return all results with &lt;code&gt;totalElements == content.size&lt;/code&gt; when passed an unpaged request:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight kotlin"&gt;&lt;code&gt;&lt;span class="kd"&gt;val&lt;/span&gt; &lt;span class="py"&gt;all&lt;/span&gt; &lt;span class="p"&gt;=&lt;/span&gt; &lt;span class="n"&gt;companyRepository&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;findAll&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nc"&gt;Pageable&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;unpaged&lt;/span&gt;&lt;span class="p"&gt;())&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h3&gt;
  
  
  Sort
&lt;/h3&gt;

&lt;p&gt;&lt;code&gt;Sort&lt;/code&gt; is immutable and composed of one or more &lt;code&gt;Sort.Order&lt;/code&gt; instances. The simplest form:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight java"&gt;&lt;code&gt;&lt;span class="nc"&gt;Sort&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;by&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="s"&gt;"name"&lt;/span&gt;&lt;span class="o"&gt;)&lt;/span&gt;                                        &lt;span class="c1"&gt;// ASC by default&lt;/span&gt;
&lt;span class="nc"&gt;Sort&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;by&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="nc"&gt;Sort&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;Direction&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;DESC&lt;/span&gt;&lt;span class="o"&gt;,&lt;/span&gt; &lt;span class="s"&gt;"name"&lt;/span&gt;&lt;span class="o"&gt;)&lt;/span&gt;
&lt;span class="nc"&gt;Sort&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;by&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="nc"&gt;Sort&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;Order&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;desc&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="s"&gt;"status"&lt;/span&gt;&lt;span class="o"&gt;),&lt;/span&gt; &lt;span class="nc"&gt;Sort&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;Order&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;asc&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="s"&gt;"name"&lt;/span&gt;&lt;span class="o"&gt;))&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;code&gt;Sort.Order&lt;/code&gt; provides fine-grained control:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight java"&gt;&lt;code&gt;&lt;span class="nc"&gt;Sort&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;Order&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;asc&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="s"&gt;"name"&lt;/span&gt;&lt;span class="o"&gt;).&lt;/span&gt;&lt;span class="na"&gt;ignoreCase&lt;/span&gt;&lt;span class="o"&gt;()&lt;/span&gt;                    &lt;span class="c1"&gt;// case-insensitive sort&lt;/span&gt;
&lt;span class="nc"&gt;Sort&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;Order&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;asc&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="s"&gt;"description"&lt;/span&gt;&lt;span class="o"&gt;).&lt;/span&gt;&lt;span class="na"&gt;nullsLast&lt;/span&gt;&lt;span class="o"&gt;()&lt;/span&gt;              &lt;span class="c1"&gt;// NULLs sorted after non-nulls&lt;/span&gt;
&lt;span class="nc"&gt;Sort&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;Order&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;desc&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="s"&gt;"description"&lt;/span&gt;&lt;span class="o"&gt;).&lt;/span&gt;&lt;span class="na"&gt;nullsFirst&lt;/span&gt;&lt;span class="o"&gt;()&lt;/span&gt;            &lt;span class="c1"&gt;// NULLs sorted before non-nulls&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Multiple fields:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight kotlin"&gt;&lt;code&gt;&lt;span class="kd"&gt;val&lt;/span&gt; &lt;span class="py"&gt;sort&lt;/span&gt; &lt;span class="p"&gt;=&lt;/span&gt; &lt;span class="nc"&gt;Sort&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="k"&gt;by&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;
    &lt;span class="nc"&gt;Sort&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nc"&gt;Order&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;desc&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s"&gt;"status"&lt;/span&gt;&lt;span class="p"&gt;),&lt;/span&gt;
    &lt;span class="nc"&gt;Sort&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nc"&gt;Order&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;asc&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s"&gt;"name"&lt;/span&gt;&lt;span class="p"&gt;).&lt;/span&gt;&lt;span class="nf"&gt;ignoreCase&lt;/span&gt;&lt;span class="p"&gt;(),&lt;/span&gt;
    &lt;span class="nc"&gt;Sort&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nc"&gt;Order&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;asc&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s"&gt;"description"&lt;/span&gt;&lt;span class="p"&gt;).&lt;/span&gt;&lt;span class="nf"&gt;nullsLast&lt;/span&gt;&lt;span class="p"&gt;()&lt;/span&gt;
&lt;span class="p"&gt;)&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Combine existing Sort instances:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight scala"&gt;&lt;code&gt;&lt;span class="k"&gt;val&lt;/span&gt; &lt;span class="nv"&gt;combined&lt;/span&gt; &lt;span class="k"&gt;=&lt;/span&gt; &lt;span class="nv"&gt;Sort&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="py"&gt;by&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="s"&gt;"name"&lt;/span&gt;&lt;span class="o"&gt;).&lt;/span&gt;&lt;span class="py"&gt;and&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="nv"&gt;Sort&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="py"&gt;by&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="nv"&gt;Sort&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="py"&gt;Direction&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="py"&gt;DESC&lt;/span&gt;&lt;span class="o"&gt;,&lt;/span&gt; &lt;span class="s"&gt;"status"&lt;/span&gt;&lt;span class="o"&gt;))&lt;/span&gt;
&lt;span class="k"&gt;val&lt;/span&gt; &lt;span class="nv"&gt;reversed&lt;/span&gt; &lt;span class="k"&gt;=&lt;/span&gt; &lt;span class="nv"&gt;Sort&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="py"&gt;by&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="s"&gt;"name"&lt;/span&gt;&lt;span class="o"&gt;).&lt;/span&gt;&lt;span class="py"&gt;reverse&lt;/span&gt;&lt;span class="o"&gt;()&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h3&gt;
  
  
  Type-safe sort with JpaSort and TypedSort
&lt;/h3&gt;

&lt;p&gt;Plain &lt;code&gt;Sort.by("name")&lt;/code&gt; is a string – a typo compiles but throws at runtime. Two type-safe alternatives exist.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;&lt;code&gt;JpaSort&lt;/code&gt;&lt;/strong&gt; uses the JPA static metamodel attributes (&lt;code&gt;Company_&lt;/code&gt;) generated by Hibernate:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight kotlin"&gt;&lt;code&gt;&lt;span class="kd"&gt;val&lt;/span&gt; &lt;span class="py"&gt;sort&lt;/span&gt; &lt;span class="p"&gt;=&lt;/span&gt; &lt;span class="nc"&gt;JpaSort&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;of&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nc"&gt;Sort&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nc"&gt;Direction&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nc"&gt;ASC&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="nc"&gt;Company_&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;name&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
&lt;span class="kd"&gt;val&lt;/span&gt; &lt;span class="py"&gt;multi&lt;/span&gt; &lt;span class="p"&gt;=&lt;/span&gt; &lt;span class="nc"&gt;JpaSort&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;of&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nc"&gt;Company_&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;name&lt;/span&gt;&lt;span class="p"&gt;).&lt;/span&gt;&lt;span class="nf"&gt;and&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nc"&gt;JpaSort&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;of&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nc"&gt;Sort&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nc"&gt;Direction&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nc"&gt;DESC&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="nc"&gt;Company_&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;status&lt;/span&gt;&lt;span class="p"&gt;))&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;If &lt;code&gt;Company_&lt;/code&gt; doesn’t have the field, the code doesn’t compile.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;&lt;code&gt;Sort.TypedSort&amp;lt;T&amp;gt;&lt;/code&gt;&lt;/strong&gt; uses method references on the entity class:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight kotlin"&gt;&lt;code&gt;&lt;span class="kd"&gt;val&lt;/span&gt; &lt;span class="py"&gt;typedSort&lt;/span&gt; &lt;span class="p"&gt;=&lt;/span&gt; &lt;span class="nc"&gt;Sort&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;sort&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nc"&gt;Company&lt;/span&gt;&lt;span class="o"&gt;::&lt;/span&gt;&lt;span class="k"&gt;class&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;java&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
&lt;span class="kd"&gt;val&lt;/span&gt; &lt;span class="py"&gt;byName&lt;/span&gt;    &lt;span class="p"&gt;=&lt;/span&gt; &lt;span class="n"&gt;typedSort&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="k"&gt;by&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nc"&gt;Company&lt;/span&gt;&lt;span class="o"&gt;::&lt;/span&gt;&lt;span class="n"&gt;name&lt;/span&gt;&lt;span class="p"&gt;).&lt;/span&gt;&lt;span class="nf"&gt;ascending&lt;/span&gt;&lt;span class="p"&gt;()&lt;/span&gt;
&lt;span class="kd"&gt;val&lt;/span&gt; &lt;span class="py"&gt;byStatus&lt;/span&gt;  &lt;span class="p"&gt;=&lt;/span&gt; &lt;span class="n"&gt;typedSort&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="k"&gt;by&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nc"&gt;Company&lt;/span&gt;&lt;span class="o"&gt;::&lt;/span&gt;&lt;span class="n"&gt;status&lt;/span&gt;&lt;span class="p"&gt;).&lt;/span&gt;&lt;span class="nf"&gt;descending&lt;/span&gt;&lt;span class="p"&gt;()&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;code&gt;TypedSort&lt;/code&gt; works only on open classes – your &lt;code&gt;allOpen&lt;/code&gt; plugin configuration already handles this for &lt;code&gt;@Entity&lt;/code&gt; classes.&lt;/p&gt;

&lt;h3&gt;
  
  
  Repository method signatures
&lt;/h3&gt;

&lt;p&gt;Declare pagination support by adding a &lt;code&gt;Pageable&lt;/code&gt; parameter and choosing the return type:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight kotlin"&gt;&lt;code&gt;&lt;span class="kd"&gt;interface&lt;/span&gt; &lt;span class="nc"&gt;CompanyRepository&lt;/span&gt; &lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="nc"&gt;JpaRepository&lt;/span&gt;&lt;span class="p"&gt;&amp;lt;&lt;/span&gt;&lt;span class="nc"&gt;Company&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="nc"&gt;UUID&lt;/span&gt;&lt;span class="p"&gt;&amp;gt;&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;

    &lt;span class="c1"&gt;// Page&amp;lt;T&amp;gt; - fires count query, returns total metadata&lt;/span&gt;
    &lt;span class="k"&gt;fun&lt;/span&gt; &lt;span class="nf"&gt;findByCountryCode&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;countryCode&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="nc"&gt;String&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;pageable&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="nc"&gt;Pageable&lt;/span&gt;&lt;span class="p"&gt;):&lt;/span&gt; &lt;span class="nc"&gt;Page&lt;/span&gt;&lt;span class="p"&gt;&amp;lt;&lt;/span&gt;&lt;span class="nc"&gt;Company&lt;/span&gt;&lt;span class="p"&gt;&amp;gt;&lt;/span&gt;

    &lt;span class="c1"&gt;// Slice&amp;lt;T&amp;gt; - no count query, only hasNext&lt;/span&gt;
    &lt;span class="c1"&gt;// Different method name required - Kotlin cannot overload by return type alone&lt;/span&gt;
    &lt;span class="k"&gt;fun&lt;/span&gt; &lt;span class="nf"&gt;findAllByCountryCode&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;countryCode&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="nc"&gt;String&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;pageable&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="nc"&gt;Pageable&lt;/span&gt;&lt;span class="p"&gt;):&lt;/span&gt; &lt;span class="nc"&gt;Slice&lt;/span&gt;&lt;span class="p"&gt;&amp;lt;&lt;/span&gt;&lt;span class="nc"&gt;Company&lt;/span&gt;&lt;span class="p"&gt;&amp;gt;&lt;/span&gt;

    &lt;span class="c1"&gt;// Custom countQuery - required when JPQL has joins or GROUP BY&lt;/span&gt;
    &lt;span class="nd"&gt;@Query&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;
        &lt;span class="n"&gt;value&lt;/span&gt; &lt;span class="p"&gt;=&lt;/span&gt; &lt;span class="s"&gt;"select c from Company c where c.countryCode = :code and c.status = :status"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
        &lt;span class="n"&gt;countQuery&lt;/span&gt; &lt;span class="p"&gt;=&lt;/span&gt; &lt;span class="s"&gt;"select count(c) from Company c where c.countryCode = :code and c.status = :status"&lt;/span&gt;
    &lt;span class="p"&gt;)&lt;/span&gt;
    &lt;span class="k"&gt;fun&lt;/span&gt; &lt;span class="nf"&gt;findActiveInCountryPaged&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;
        &lt;span class="nd"&gt;@Param&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s"&gt;"code"&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="n"&gt;countryCode&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="nc"&gt;String&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
        &lt;span class="nd"&gt;@Param&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s"&gt;"status"&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="n"&gt;status&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="nc"&gt;CompanyStatus&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
        &lt;span class="n"&gt;pageable&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="nc"&gt;Pageable&lt;/span&gt;
    &lt;span class="p"&gt;):&lt;/span&gt; &lt;span class="nc"&gt;Page&lt;/span&gt;&lt;span class="p"&gt;&amp;lt;&lt;/span&gt;&lt;span class="nc"&gt;Company&lt;/span&gt;&lt;span class="p"&gt;&amp;gt;&lt;/span&gt;
&lt;span class="p"&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;For queries involving &lt;code&gt;JOIN&lt;/code&gt;, &lt;code&gt;DISTINCT&lt;/code&gt;, or &lt;code&gt;GROUP BY&lt;/code&gt;, auto-derived count queries frequently produce wrong results – provide an explicit &lt;code&gt;countQuery&lt;/code&gt;. Native SQL queries always require one since Spring Data’s built-in enhancer handles only simple queries for count derivation.&lt;/p&gt;

&lt;h3&gt;
  
  
  Count query optimization
&lt;/h3&gt;

&lt;p&gt;Spring Data will skip the &lt;code&gt;COUNT&lt;/code&gt; query automatically when the result is a partial page (fewer rows than the requested page size). If the current page is not full, the total can be inferred without hitting the database:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;First page, partial result → &lt;code&gt;totalElements = content.size&lt;/code&gt;
&lt;/li&gt;
&lt;li&gt;Any other page, partial result → &lt;code&gt;totalElements = offset + content.size&lt;/code&gt;
&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;The count query only fires when the page is full and the total is genuinely unknown.&lt;/p&gt;

&lt;h3&gt;
  
  
  Common pitfalls wigh Spring Data JPA pagination and sorting
&lt;/h3&gt;

&lt;p&gt;&lt;strong&gt;&lt;code&gt;join fetch&lt;/code&gt; with &lt;code&gt;Page&amp;lt;T&amp;gt;&lt;/code&gt;&lt;/strong&gt; – never combine &lt;code&gt;JOIN FETCH&lt;/code&gt; on a collection association with a paginated query returning &lt;code&gt;Page&amp;lt;T&amp;gt;&lt;/code&gt;. Hibernate cannot apply &lt;code&gt;LIMIT/OFFSET&lt;/code&gt; at the SQL level when a collection is eagerly fetched in the same query, so it loads all matching rows into memory first and then paginates in Java. On large datasets, this causes out-of-memory errors. Hibernate logs a warning: &lt;code&gt;HHH90003004: firstResult/maxResults specified with collection fetch; applying in memory&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Sorting by non-persistent fields&lt;/strong&gt; – &lt;code&gt;Sort.by("computedField")&lt;/code&gt; throws &lt;code&gt;PropertyReferenceException&lt;/code&gt; at runtime if the field does not exist on the entity. Use &lt;code&gt;JpaSort&lt;/code&gt; with metamodel attributes to catch this at compile time.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Returning &lt;code&gt;PageImpl&lt;/code&gt; directly from controllers&lt;/strong&gt; – &lt;code&gt;PageImpl&lt;/code&gt; is not a stable serialization contract and its JSON shape can change between Spring Data versions. Map to an explicit DTO or configure page serialization mode explicitly:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;strong&gt;&lt;code&gt;DIRECT&lt;/code&gt;&lt;/strong&gt; (default): serializes &lt;code&gt;PageImpl&lt;/code&gt; directly; the JSON shape includes Spring Data internals and is not guaranteed stable between versions.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;&lt;code&gt;VIA_DTO&lt;/code&gt;&lt;/strong&gt;: wraps the result in a documented, stable DTO shape – the recommended choice for API responses.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;The default is &lt;code&gt;DIRECT&lt;/code&gt; for backward compatibility. Set &lt;code&gt;VIA_DTO&lt;/code&gt; explicitly:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight yaml"&gt;&lt;code&gt;&lt;span class="na"&gt;spring&lt;/span&gt;&lt;span class="pi"&gt;:&lt;/span&gt;
  &lt;span class="na"&gt;data&lt;/span&gt;&lt;span class="pi"&gt;:&lt;/span&gt;
    &lt;span class="na"&gt;web&lt;/span&gt;&lt;span class="pi"&gt;:&lt;/span&gt;
      &lt;span class="na"&gt;pageable&lt;/span&gt;&lt;span class="pi"&gt;:&lt;/span&gt;
        &lt;span class="na"&gt;serialization-mode&lt;/span&gt;&lt;span class="pi"&gt;:&lt;/span&gt; &lt;span class="s"&gt;via-dto&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  Dynamic Filtering with Spring Data JPA Specifications
&lt;/h2&gt;

&lt;p&gt;Derived query methods and &lt;code&gt;@Query&lt;/code&gt; work well for fixed filters. When filters are optional or the combination changes at runtime – for example, a search endpoint where the user can filter by status, country, or name in any combination – you need a different approach.&lt;/p&gt;

&lt;h3&gt;
  
  
  JpaSpecificationExecutor
&lt;/h3&gt;

&lt;p&gt;&lt;code&gt;JpaSpecificationExecutor&amp;lt;T&amp;gt;&lt;/code&gt; is Spring Data JPA’s built-in option for dynamic filtering. Add it alongside &lt;code&gt;JpaRepository&lt;/code&gt; in your repository interface – no extra dependencies needed:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight java"&gt;&lt;code&gt;&lt;span class="kd"&gt;interface&lt;/span&gt; &lt;span class="nc"&gt;CompanyRepository&lt;/span&gt; &lt;span class="o"&gt;:&lt;/span&gt;
    &lt;span class="nc"&gt;JpaRepository&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="nc"&gt;Company&lt;/span&gt;&lt;span class="o"&gt;,&lt;/span&gt; &lt;span class="no"&gt;UUID&lt;/span&gt;&lt;span class="o"&gt;&amp;gt;,&lt;/span&gt;
    &lt;span class="nc"&gt;JpaSpecificationExecutor&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="nc"&gt;Company&lt;/span&gt;&lt;span class="o"&gt;&amp;gt;&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;This adds &lt;code&gt;findAll(spec)&lt;/code&gt;, &lt;code&gt;findAll(spec, pageable)&lt;/code&gt;, &lt;code&gt;count(spec)&lt;/code&gt;, &lt;code&gt;exists(spec)&lt;/code&gt;, &lt;code&gt;delete(spec)&lt;/code&gt;, and &lt;code&gt;update(spec)&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;A &lt;code&gt;Specification&lt;/code&gt; is a lambda that receives a JPA Criteria API &lt;code&gt;Root&lt;/code&gt;, &lt;code&gt;CriteriaQuery&lt;/code&gt;, and &lt;code&gt;CriteriaBuilder&lt;/code&gt; and returns a &lt;code&gt;Predicate&lt;/code&gt;. Without the type-safe metamodel, field access uses string literals:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight kotlin"&gt;&lt;code&gt;&lt;span class="kd"&gt;val&lt;/span&gt; &lt;span class="py"&gt;spec&lt;/span&gt; &lt;span class="p"&gt;=&lt;/span&gt; &lt;span class="nc"&gt;Specification&lt;/span&gt;&lt;span class="p"&gt;&amp;lt;&lt;/span&gt;&lt;span class="nc"&gt;Company&lt;/span&gt;&lt;span class="p"&gt;&amp;gt;&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt; &lt;span class="n"&gt;root&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;_&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;cb&lt;/span&gt; &lt;span class="p"&gt;-&amp;gt;&lt;/span&gt;
    &lt;span class="n"&gt;cb&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;equal&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;root&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="k"&gt;get&lt;/span&gt;&lt;span class="p"&gt;&amp;lt;&lt;/span&gt;&lt;span class="nc"&gt;CompanyStatus&lt;/span&gt;&lt;span class="p"&gt;&amp;gt;(&lt;/span&gt;&lt;span class="s"&gt;"status"&lt;/span&gt;&lt;span class="p"&gt;),&lt;/span&gt; &lt;span class="nc"&gt;CompanyStatus&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nc"&gt;ACTIVE&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="c1"&gt;// fragile string&lt;/span&gt;
&lt;span class="p"&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;A typo in &lt;code&gt;"status"&lt;/code&gt; compiles fine but throws at runtime. The solution is the &lt;strong&gt;JPA static metamodel&lt;/strong&gt;.&lt;/p&gt;

&lt;h3&gt;
  
  
  JPA static metamodel
&lt;/h3&gt;

&lt;p&gt;Hibernate’s annotation processor generates a &lt;code&gt;Company_&lt;/code&gt; class from your &lt;code&gt;@Entity&lt;/code&gt; at build time. Each field becomes a typed &lt;code&gt;SingularAttribute&lt;/code&gt; instead of a string:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight java"&gt;&lt;code&gt;&lt;span class="c1"&gt;// Generated: Company_.java&lt;/span&gt;
&lt;span class="nd"&gt;@StaticMetamodel&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="nc"&gt;Company&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;class&lt;/span&gt;&lt;span class="o"&gt;)&lt;/span&gt;
&lt;span class="nd"&gt;@Generated&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="s"&gt;"org.hibernate.processor.HibernateProcessor"&lt;/span&gt;&lt;span class="o"&gt;)&lt;/span&gt;
&lt;span class="kd"&gt;public&lt;/span&gt; &lt;span class="kd"&gt;abstract&lt;/span&gt; &lt;span class="kd"&gt;class&lt;/span&gt; &lt;span class="nc"&gt;Company_&lt;/span&gt; &lt;span class="o"&gt;{&lt;/span&gt;

    &lt;span class="kd"&gt;public&lt;/span&gt; &lt;span class="kd"&gt;static&lt;/span&gt; &lt;span class="kd"&gt;final&lt;/span&gt; &lt;span class="nc"&gt;String&lt;/span&gt; &lt;span class="no"&gt;NAME&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="s"&gt;"name"&lt;/span&gt;&lt;span class="o"&gt;;&lt;/span&gt;
    &lt;span class="kd"&gt;public&lt;/span&gt; &lt;span class="kd"&gt;static&lt;/span&gt; &lt;span class="kd"&gt;final&lt;/span&gt; &lt;span class="nc"&gt;String&lt;/span&gt; &lt;span class="no"&gt;COUNTRY_CODE&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="s"&gt;"countryCode"&lt;/span&gt;&lt;span class="o"&gt;;&lt;/span&gt;
    &lt;span class="kd"&gt;public&lt;/span&gt; &lt;span class="kd"&gt;static&lt;/span&gt; &lt;span class="kd"&gt;final&lt;/span&gt; &lt;span class="nc"&gt;String&lt;/span&gt; &lt;span class="no"&gt;STATUS&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="s"&gt;"status"&lt;/span&gt;&lt;span class="o"&gt;;&lt;/span&gt;
    &lt;span class="kd"&gt;public&lt;/span&gt; &lt;span class="kd"&gt;static&lt;/span&gt; &lt;span class="kd"&gt;final&lt;/span&gt; &lt;span class="nc"&gt;String&lt;/span&gt; &lt;span class="no"&gt;DESCRIPTION&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="s"&gt;"description"&lt;/span&gt;&lt;span class="o"&gt;;&lt;/span&gt;
    &lt;span class="kd"&gt;public&lt;/span&gt; &lt;span class="kd"&gt;static&lt;/span&gt; &lt;span class="kd"&gt;final&lt;/span&gt; &lt;span class="nc"&gt;String&lt;/span&gt; &lt;span class="no"&gt;ID&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="s"&gt;"id"&lt;/span&gt;&lt;span class="o"&gt;;&lt;/span&gt;

    &lt;span class="kd"&gt;public&lt;/span&gt; &lt;span class="kd"&gt;static&lt;/span&gt; &lt;span class="kd"&gt;volatile&lt;/span&gt; &lt;span class="nc"&gt;EntityType&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="nc"&gt;Company&lt;/span&gt;&lt;span class="o"&gt;&amp;gt;&lt;/span&gt; &lt;span class="n"&gt;class_&lt;/span&gt;&lt;span class="o"&gt;;&lt;/span&gt;
    &lt;span class="kd"&gt;public&lt;/span&gt; &lt;span class="kd"&gt;static&lt;/span&gt; &lt;span class="kd"&gt;volatile&lt;/span&gt; &lt;span class="nc"&gt;SingularAttribute&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="nc"&gt;Company&lt;/span&gt;&lt;span class="o"&gt;,&lt;/span&gt; &lt;span class="nc"&gt;String&lt;/span&gt;&lt;span class="o"&gt;&amp;gt;&lt;/span&gt; &lt;span class="n"&gt;name&lt;/span&gt;&lt;span class="o"&gt;;&lt;/span&gt;
    &lt;span class="kd"&gt;public&lt;/span&gt; &lt;span class="kd"&gt;static&lt;/span&gt; &lt;span class="kd"&gt;volatile&lt;/span&gt; &lt;span class="nc"&gt;SingularAttribute&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="nc"&gt;Company&lt;/span&gt;&lt;span class="o"&gt;,&lt;/span&gt; &lt;span class="nc"&gt;String&lt;/span&gt;&lt;span class="o"&gt;&amp;gt;&lt;/span&gt; &lt;span class="n"&gt;countryCode&lt;/span&gt;&lt;span class="o"&gt;;&lt;/span&gt;
    &lt;span class="kd"&gt;public&lt;/span&gt; &lt;span class="kd"&gt;static&lt;/span&gt; &lt;span class="kd"&gt;volatile&lt;/span&gt; &lt;span class="nc"&gt;SingularAttribute&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="nc"&gt;Company&lt;/span&gt;&lt;span class="o"&gt;,&lt;/span&gt; &lt;span class="nc"&gt;CompanyStatus&lt;/span&gt;&lt;span class="o"&gt;&amp;gt;&lt;/span&gt; &lt;span class="n"&gt;status&lt;/span&gt;&lt;span class="o"&gt;;&lt;/span&gt;
    &lt;span class="kd"&gt;public&lt;/span&gt; &lt;span class="kd"&gt;static&lt;/span&gt; &lt;span class="kd"&gt;volatile&lt;/span&gt; &lt;span class="nc"&gt;SingularAttribute&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="nc"&gt;Company&lt;/span&gt;&lt;span class="o"&gt;,&lt;/span&gt; &lt;span class="nc"&gt;String&lt;/span&gt;&lt;span class="o"&gt;&amp;gt;&lt;/span&gt; &lt;span class="n"&gt;description&lt;/span&gt;&lt;span class="o"&gt;;&lt;/span&gt;
    &lt;span class="kd"&gt;public&lt;/span&gt; &lt;span class="kd"&gt;static&lt;/span&gt; &lt;span class="kd"&gt;volatile&lt;/span&gt; &lt;span class="nc"&gt;SingularAttribute&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="nc"&gt;Company&lt;/span&gt;&lt;span class="o"&gt;,&lt;/span&gt; &lt;span class="no"&gt;UUID&lt;/span&gt;&lt;span class="o"&gt;&amp;gt;&lt;/span&gt; &lt;span class="n"&gt;id&lt;/span&gt;&lt;span class="o"&gt;;&lt;/span&gt;
&lt;span class="o"&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;With the metamodel, field access is type-checked at compile time:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight kotlin"&gt;&lt;code&gt;&lt;span class="kd"&gt;val&lt;/span&gt; &lt;span class="py"&gt;spec&lt;/span&gt; &lt;span class="p"&gt;=&lt;/span&gt; &lt;span class="nc"&gt;Specification&lt;/span&gt;&lt;span class="p"&gt;&amp;lt;&lt;/span&gt;&lt;span class="nc"&gt;Company&lt;/span&gt;&lt;span class="p"&gt;&amp;gt;&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt; &lt;span class="n"&gt;root&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;_&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;cb&lt;/span&gt; &lt;span class="p"&gt;-&amp;gt;&lt;/span&gt;
    &lt;span class="n"&gt;cb&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;equal&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;root&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="k"&gt;get&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nc"&gt;Company_&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;status&lt;/span&gt;&lt;span class="p"&gt;),&lt;/span&gt; &lt;span class="nc"&gt;CompanyStatus&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nc"&gt;ACTIVE&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="c1"&gt;// compile-time safe&lt;/span&gt;
&lt;span class="p"&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Rename &lt;code&gt;status&lt;/code&gt; in &lt;code&gt;Company&lt;/code&gt; and the compiler immediately flags &lt;code&gt;Company_.status&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;Gradle setup (kapt – &lt;code&gt;hibernate-processor&lt;/code&gt; version is managed by the Spring Boot BOM):&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight gradle"&gt;&lt;code&gt;&lt;span class="n"&gt;plugins&lt;/span&gt; &lt;span class="o"&gt;{&lt;/span&gt;
    &lt;span class="n"&gt;kotlin&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="s2"&gt;"kapt"&lt;/span&gt;&lt;span class="o"&gt;)&lt;/span&gt;
&lt;span class="o"&gt;}&lt;/span&gt;

&lt;span class="k"&gt;dependencies&lt;/span&gt; &lt;span class="o"&gt;{&lt;/span&gt;
    &lt;span class="n"&gt;kapt&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="s2"&gt;"org.hibernate.orm:hibernate-processor"&lt;/span&gt;&lt;span class="o"&gt;)&lt;/span&gt;
&lt;span class="o"&gt;}&lt;/span&gt;

&lt;span class="n"&gt;kapt&lt;/span&gt; &lt;span class="o"&gt;{&lt;/span&gt;
    &lt;span class="n"&gt;correctErrorTypes&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="kc"&gt;true&lt;/span&gt;
&lt;span class="o"&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;After building, kapt generates &lt;code&gt;Company_.java&lt;/code&gt; in &lt;code&gt;build/generated/source/kapt/main/&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;Specifications compose with &lt;code&gt;.and()&lt;/code&gt; and &lt;code&gt;.or()&lt;/code&gt;. For negation, use the static &lt;code&gt;Specification.not(...)&lt;/code&gt; helper:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight kotlin"&gt;&lt;code&gt;&lt;span class="kd"&gt;object&lt;/span&gt; &lt;span class="nc"&gt;CompanySpecs&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
    &lt;span class="k"&gt;fun&lt;/span&gt; &lt;span class="nf"&gt;hasStatus&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;status&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="nc"&gt;CompanyStatus&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="p"&gt;=&lt;/span&gt; &lt;span class="nc"&gt;Specification&lt;/span&gt;&lt;span class="p"&gt;&amp;lt;&lt;/span&gt;&lt;span class="nc"&gt;Company&lt;/span&gt;&lt;span class="p"&gt;&amp;gt;&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt; &lt;span class="n"&gt;root&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;_&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;cb&lt;/span&gt; &lt;span class="p"&gt;-&amp;gt;&lt;/span&gt;
        &lt;span class="n"&gt;cb&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;equal&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;root&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="k"&gt;get&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nc"&gt;Company_&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;status&lt;/span&gt;&lt;span class="p"&gt;),&lt;/span&gt; &lt;span class="n"&gt;status&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
    &lt;span class="p"&gt;}&lt;/span&gt;

    &lt;span class="k"&gt;fun&lt;/span&gt; &lt;span class="nf"&gt;hasCountryCode&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;code&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="nc"&gt;String&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="p"&gt;=&lt;/span&gt; &lt;span class="nc"&gt;Specification&lt;/span&gt;&lt;span class="p"&gt;&amp;lt;&lt;/span&gt;&lt;span class="nc"&gt;Company&lt;/span&gt;&lt;span class="p"&gt;&amp;gt;&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt; &lt;span class="n"&gt;root&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;_&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;cb&lt;/span&gt; &lt;span class="p"&gt;-&amp;gt;&lt;/span&gt;
        &lt;span class="n"&gt;cb&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;equal&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;root&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="k"&gt;get&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nc"&gt;Company_&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;countryCode&lt;/span&gt;&lt;span class="p"&gt;),&lt;/span&gt; &lt;span class="n"&gt;code&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
    &lt;span class="p"&gt;}&lt;/span&gt;
&lt;span class="p"&gt;}&lt;/span&gt;

&lt;span class="c1"&gt;// Usage&lt;/span&gt;
&lt;span class="kd"&gt;val&lt;/span&gt; &lt;span class="py"&gt;result&lt;/span&gt; &lt;span class="p"&gt;=&lt;/span&gt; &lt;span class="n"&gt;companyRepository&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;findAll&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;
    &lt;span class="nc"&gt;CompanySpecs&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;hasCountryCode&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s"&gt;"DE"&lt;/span&gt;&lt;span class="p"&gt;).&lt;/span&gt;&lt;span class="nf"&gt;and&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nc"&gt;CompanySpecs&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;hasStatus&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nc"&gt;CompanyStatus&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nc"&gt;ACTIVE&lt;/span&gt;&lt;span class="p"&gt;))&lt;/span&gt;
&lt;span class="p"&gt;)&lt;/span&gt;

&lt;span class="kd"&gt;val&lt;/span&gt; &lt;span class="py"&gt;notSuspended&lt;/span&gt; &lt;span class="p"&gt;=&lt;/span&gt; &lt;span class="n"&gt;companyRepository&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;findAll&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;
    &lt;span class="nc"&gt;Specification&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;not&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nc"&gt;CompanySpecs&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;hasStatus&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nc"&gt;CompanyStatus&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nc"&gt;SUSPENDED&lt;/span&gt;&lt;span class="p"&gt;))&lt;/span&gt;
&lt;span class="p"&gt;)&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;For optional filters, returning &lt;code&gt;null&lt;/code&gt; from a &lt;code&gt;Specification&lt;/code&gt; lambda skips the predicate entirely – JPA treats a &lt;code&gt;null&lt;/code&gt; predicate as no restriction:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight kotlin"&gt;&lt;code&gt;&lt;span class="k"&gt;fun&lt;/span&gt; &lt;span class="nf"&gt;hasCountryCodeOptional&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;code&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="nc"&gt;String&lt;/span&gt;&lt;span class="p"&gt;?)&lt;/span&gt; &lt;span class="p"&gt;=&lt;/span&gt; &lt;span class="nc"&gt;Specification&lt;/span&gt;&lt;span class="p"&gt;&amp;lt;&lt;/span&gt;&lt;span class="nc"&gt;Company&lt;/span&gt;&lt;span class="p"&gt;&amp;gt;&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt; &lt;span class="n"&gt;root&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;_&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;cb&lt;/span&gt; &lt;span class="p"&gt;-&amp;gt;&lt;/span&gt;
    &lt;span class="k"&gt;if&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;code&lt;/span&gt; &lt;span class="p"&gt;!=&lt;/span&gt; &lt;span class="k"&gt;null&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="n"&gt;cb&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;equal&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;root&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="k"&gt;get&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nc"&gt;Company_&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;countryCode&lt;/span&gt;&lt;span class="p"&gt;),&lt;/span&gt; &lt;span class="n"&gt;code&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="k"&gt;else&lt;/span&gt; &lt;span class="k"&gt;null&lt;/span&gt;
&lt;span class="p"&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;When to use Specifications:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;You want zero extra runtime dependencies – everything is built into Spring Data JPA and Hibernate.&lt;/li&gt;
&lt;li&gt;You need bulk &lt;code&gt;delete&lt;/code&gt; or &lt;code&gt;update&lt;/code&gt; via &lt;code&gt;DeleteSpecification&lt;/code&gt; / &lt;code&gt;UpdateSpecification&lt;/code&gt;. Spring Data JPA 4.0 also introduced &lt;code&gt;PredicateSpecification&lt;/code&gt; – a query-type-agnostic variant that works across select, update, and delete queries without being tied to a single operation type.&lt;/li&gt;
&lt;li&gt;You prefer a standardised JPA approach over a third-party query DSL.&lt;/li&gt;
&lt;/ul&gt;

&lt;h3&gt;
  
  
  QueryDSL with Spring Data JPA
&lt;/h3&gt;

&lt;p&gt;QueryDSL generates type-safe Q-classes from your JPA entities at build time. Instead of writing query conditions as string literals (which break silently on refactoring), you reference real Kotlin properties – &lt;code&gt;QCompany.company.countryCode&lt;/code&gt; – that fail to compile if the field is renamed or removed.&lt;/p&gt;

&lt;p&gt;QueryDSL solves the same problem as Specifications but with a more readable fluent API: one method, any filter combination, all type-checked at compile time.&lt;/p&gt;

&lt;p&gt;Gradle setup (kapt for Q-class generation):&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight gradle"&gt;&lt;code&gt;&lt;span class="n"&gt;plugins&lt;/span&gt; &lt;span class="o"&gt;{&lt;/span&gt;
    &lt;span class="n"&gt;kotlin&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="s2"&gt;"kapt"&lt;/span&gt;&lt;span class="o"&gt;)&lt;/span&gt;
&lt;span class="o"&gt;}&lt;/span&gt;

&lt;span class="k"&gt;dependencies&lt;/span&gt; &lt;span class="o"&gt;{&lt;/span&gt;
    &lt;span class="n"&gt;implementation&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="s2"&gt;"com.querydsl:querydsl-jpa::jakarta"&lt;/span&gt;&lt;span class="o"&gt;)&lt;/span&gt;
    &lt;span class="n"&gt;kapt&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="s2"&gt;"com.querydsl:querydsl-apt::jakarta"&lt;/span&gt;&lt;span class="o"&gt;)&lt;/span&gt;
    &lt;span class="n"&gt;kapt&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="s2"&gt;"jakarta.persistence:jakarta.persistence-api"&lt;/span&gt;&lt;span class="o"&gt;)&lt;/span&gt;
&lt;span class="o"&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The &lt;code&gt;::jakarta&lt;/code&gt; notation omits the version – it is managed by the Spring Boot BOM. The &lt;code&gt;jakarta&lt;/code&gt; classifier selects the Jakarta EE 9+ variant required for Spring Boot 3.x/4.x. After building, kapt generates a &lt;code&gt;QCompany&lt;/code&gt; class alongside your entity.&lt;/p&gt;

&lt;p&gt;Add &lt;code&gt;QuerydslPredicateExecutor&amp;lt;T&amp;gt;&lt;/code&gt; to your repository:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight java"&gt;&lt;code&gt;&lt;span class="kd"&gt;interface&lt;/span&gt; &lt;span class="nc"&gt;CompanyRepository&lt;/span&gt; &lt;span class="o"&gt;:&lt;/span&gt;
    &lt;span class="nc"&gt;JpaRepository&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="nc"&gt;Company&lt;/span&gt;&lt;span class="o"&gt;,&lt;/span&gt; &lt;span class="no"&gt;UUID&lt;/span&gt;&lt;span class="o"&gt;&amp;gt;,&lt;/span&gt;
    &lt;span class="nc"&gt;QuerydslPredicateExecutor&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="nc"&gt;Company&lt;/span&gt;&lt;span class="o"&gt;&amp;gt;&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;This adds &lt;code&gt;findAll(predicate)&lt;/code&gt;, &lt;code&gt;findAll(predicate, pageable)&lt;/code&gt;, &lt;code&gt;count(predicate)&lt;/code&gt;, and &lt;code&gt;exists(predicate)&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;After building, kapt generates &lt;code&gt;QCompany&lt;/code&gt;. Use &lt;code&gt;BooleanBuilder&lt;/code&gt; for optional filters:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight kotlin"&gt;&lt;code&gt;&lt;span class="k"&gt;fun&lt;/span&gt; &lt;span class="nf"&gt;searchCompanies&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;
    &lt;span class="n"&gt;countryCode&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="nc"&gt;String&lt;/span&gt;&lt;span class="p"&gt;?,&lt;/span&gt;
    &lt;span class="n"&gt;status&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="nc"&gt;CompanyStatus&lt;/span&gt;&lt;span class="p"&gt;?,&lt;/span&gt;
    &lt;span class="n"&gt;pageable&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="nc"&gt;Pageable&lt;/span&gt;
&lt;span class="p"&gt;):&lt;/span&gt; &lt;span class="nc"&gt;Page&lt;/span&gt;&lt;span class="p"&gt;&amp;lt;&lt;/span&gt;&lt;span class="nc"&gt;Company&lt;/span&gt;&lt;span class="p"&gt;&amp;gt;&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
    &lt;span class="kd"&gt;val&lt;/span&gt; &lt;span class="py"&gt;q&lt;/span&gt; &lt;span class="p"&gt;=&lt;/span&gt; &lt;span class="nc"&gt;QCompany&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;company&lt;/span&gt;
    &lt;span class="kd"&gt;val&lt;/span&gt; &lt;span class="py"&gt;predicate&lt;/span&gt; &lt;span class="p"&gt;=&lt;/span&gt; &lt;span class="nc"&gt;BooleanBuilder&lt;/span&gt;&lt;span class="p"&gt;()&lt;/span&gt;
    &lt;span class="n"&gt;countryCode&lt;/span&gt;&lt;span class="o"&gt;?.&lt;/span&gt;&lt;span class="nf"&gt;let&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt; &lt;span class="n"&gt;predicate&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;and&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;q&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;countryCode&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;eq&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;it&lt;/span&gt;&lt;span class="p"&gt;))&lt;/span&gt; &lt;span class="p"&gt;}&lt;/span&gt;
    &lt;span class="n"&gt;status&lt;/span&gt;&lt;span class="o"&gt;?.&lt;/span&gt;&lt;span class="nf"&gt;let&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt; &lt;span class="n"&gt;predicate&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;and&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;q&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;status&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;eq&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;it&lt;/span&gt;&lt;span class="p"&gt;))&lt;/span&gt; &lt;span class="p"&gt;}&lt;/span&gt;
    &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="n"&gt;companyRepository&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;findAll&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;predicate&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;pageable&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
&lt;span class="p"&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;An empty &lt;code&gt;BooleanBuilder&lt;/code&gt; matches all rows – document this on filter methods so callers know no filter means no restriction.&lt;/p&gt;

&lt;h2&gt;
  
  
  Spring Data JPA Projections in Kotlin
&lt;/h2&gt;

&lt;p&gt;Projections are specialized read models (DTOs) for data exchange with clients. Returning raw entities directly is usually a bad practice for public APIs because it leaks persistence details and often exposes more fields than needed.&lt;/p&gt;

&lt;p&gt;Where projections fit in:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;A projection is a read-focused DTO/view shape requested directly from the database query.&lt;/li&gt;
&lt;li&gt;In practice, projections are often the most direct DTO path for read APIs when the query selects only required columns.&lt;/li&gt;
&lt;li&gt;Important nuance: DB load is reduced only if the query selects fewer columns. Fetching full entities and mapping afterward does &lt;strong&gt;not&lt;/strong&gt; reduce selected columns.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;A bit more about trade-offs: more DTO/projection types improve API clarity and performance, but they increase maintenance cost, so define them per use case (summary/detail/list item) instead of one mega-DTO.&lt;/p&gt;

&lt;h3&gt;
  
  
  Interface-based projection (read-only view)
&lt;/h3&gt;

&lt;p&gt;An interface-based projection is a plain Kotlin interface where each property getter matches a field name in the entity. Spring Data JPA generates a proxy at runtime that implements the interface and maps query results onto it automatically – no constructor, no mapper, no extra class needed.&lt;/p&gt;

&lt;p&gt;When all accessor methods map directly to entity properties, this is called a &lt;strong&gt;closed projection&lt;/strong&gt; in Spring Data JPA terminology. Because Spring Data knows exactly which fields are needed, it can optimize the query and select only the projected fields – skipping any columns not declared in the interface.&lt;/p&gt;

&lt;p&gt;Column reduction depends on how the query is written:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;strong&gt;Derived query methods&lt;/strong&gt; – Spring Data automatically generates a &lt;code&gt;SELECT&lt;/code&gt; that fetches only the fields declared in the interface.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;&lt;code&gt;@Query("select c from Company c ...")&lt;/code&gt;&lt;/strong&gt; – loads all columns and wraps the full entity in a proxy. No column reduction happens.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;&lt;code&gt;@Query&lt;/code&gt; with explicit field selection&lt;/strong&gt; – fetches only the listed fields. This is the correct way to get column reduction with a custom query.
&lt;/li&gt;
&lt;/ul&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight kotlin"&gt;&lt;code&gt;&lt;span class="kd"&gt;interface&lt;/span&gt; &lt;span class="nc"&gt;CompanySummaryView&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
    &lt;span class="kd"&gt;val&lt;/span&gt; &lt;span class="py"&gt;id&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="nc"&gt;UUID&lt;/span&gt;
    &lt;span class="kd"&gt;val&lt;/span&gt; &lt;span class="py"&gt;name&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="nc"&gt;String&lt;/span&gt;
    &lt;span class="kd"&gt;val&lt;/span&gt; &lt;span class="py"&gt;countryCode&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="nc"&gt;String&lt;/span&gt;
    &lt;span class="kd"&gt;val&lt;/span&gt; &lt;span class="py"&gt;status&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="nc"&gt;CompanyStatus&lt;/span&gt;
&lt;span class="p"&gt;}&lt;/span&gt;

&lt;span class="c1"&gt;// Derived - Spring Data selects only the four declared fields&lt;/span&gt;
&lt;span class="k"&gt;fun&lt;/span&gt; &lt;span class="nf"&gt;findByCountryCode&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;countryCode&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="nc"&gt;String&lt;/span&gt;&lt;span class="p"&gt;):&lt;/span&gt; &lt;span class="nc"&gt;List&lt;/span&gt;&lt;span class="p"&gt;&amp;lt;&lt;/span&gt;&lt;span class="nc"&gt;CompanySummaryView&lt;/span&gt;&lt;span class="p"&gt;&amp;gt;&lt;/span&gt;

&lt;span class="c1"&gt;// @Query with explicit fields - also reduces columns&lt;/span&gt;
&lt;span class="nd"&gt;@Query&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s"&gt;"""
    select c.id as id, c.name as name, c.countryCode as countryCode, c.status as status
    from Company c where c.countryCode = :countryCode
"""&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
&lt;span class="k"&gt;fun&lt;/span&gt; &lt;span class="nf"&gt;findSummaryByCountryCode&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nd"&gt;@Param&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s"&gt;"countryCode"&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="n"&gt;countryCode&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="nc"&gt;String&lt;/span&gt;&lt;span class="p"&gt;):&lt;/span&gt; &lt;span class="nc"&gt;List&lt;/span&gt;&lt;span class="p"&gt;&amp;lt;&lt;/span&gt;&lt;span class="nc"&gt;CompanySummaryView&lt;/span&gt;&lt;span class="p"&gt;&amp;gt;&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Kotlin note: you cannot declare two methods with the same name and same parameters differing only by return type. If &lt;code&gt;findByCountryCode(countryCode: String): List&amp;lt;Company&amp;gt;&lt;/code&gt; already exists, you need a distinct method name for the projection overload – as shown with &lt;code&gt;findSummaryByCountryCode&lt;/code&gt; above.&lt;/p&gt;

&lt;p&gt;You can also transform or combine columns in the query and map the result to the interface by matching the alias name:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight kotlin"&gt;&lt;code&gt;&lt;span class="kd"&gt;interface&lt;/span&gt; &lt;span class="nc"&gt;CompanyListView&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
    &lt;span class="kd"&gt;val&lt;/span&gt; &lt;span class="py"&gt;id&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="nc"&gt;UUID&lt;/span&gt;
    &lt;span class="kd"&gt;val&lt;/span&gt; &lt;span class="py"&gt;displayName&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="nc"&gt;String&lt;/span&gt;
&lt;span class="p"&gt;}&lt;/span&gt;

&lt;span class="nd"&gt;@Query&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s"&gt;"select c.id as id, concat(c.name, ' (', c.countryCode, ')') as displayName from Company c"&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
&lt;span class="k"&gt;fun&lt;/span&gt; &lt;span class="nf"&gt;findAllForList&lt;/span&gt;&lt;span class="p"&gt;():&lt;/span&gt; &lt;span class="nc"&gt;List&lt;/span&gt;&lt;span class="p"&gt;&amp;lt;&lt;/span&gt;&lt;span class="nc"&gt;CompanyListView&lt;/span&gt;&lt;span class="p"&gt;&amp;gt;&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;When to use:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Simple read-only list and summary API responses where all fields map directly to entity properties or returned from database.&lt;/li&gt;
&lt;li&gt;When you want minimal boilerplate – no DTO class, no constructor, no mapper required.&lt;/li&gt;
&lt;/ul&gt;

&lt;h3&gt;
  
  
  Class/DTO projection with Spring Data JPA
&lt;/h3&gt;

&lt;p&gt;A class-based projection is a regular Kotlin &lt;code&gt;data class&lt;/code&gt; used as the query result type directly. Instead of returning entities and mapping them afterward, you instruct JPQL to construct the DTO inline using the &lt;code&gt;new&lt;/code&gt; keyword with a fully qualified class name. Class-based projections use JPA’s constructor expression mechanism to create DTO instances – no interface proxy is created. The response model is completely decoupled from the entity.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight kotlin"&gt;&lt;code&gt;&lt;span class="kd"&gt;data class&lt;/span&gt; &lt;span class="nc"&gt;CompanySummaryDto&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;
    &lt;span class="kd"&gt;val&lt;/span&gt; &lt;span class="py"&gt;id&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="nc"&gt;UUID&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
    &lt;span class="kd"&gt;val&lt;/span&gt; &lt;span class="py"&gt;name&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="nc"&gt;String&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
    &lt;span class="kd"&gt;val&lt;/span&gt; &lt;span class="py"&gt;countryCode&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="nc"&gt;String&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
    &lt;span class="kd"&gt;val&lt;/span&gt; &lt;span class="py"&gt;status&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="nc"&gt;CompanyStatus&lt;/span&gt;
&lt;span class="p"&gt;)&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;





&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight kotlin"&gt;&lt;code&gt;&lt;span class="nd"&gt;@Query&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;
    &lt;span class="s"&gt;"""
    select new dev.protsenko.jpa.CompanySummaryDto(c.id, c.name, c.countryCode, c.status)
    from Company c
    where c.countryCode = :countryCode
    """&lt;/span&gt;
&lt;span class="p"&gt;)&lt;/span&gt;
&lt;span class="k"&gt;fun&lt;/span&gt; &lt;span class="nf"&gt;findCompanySummaries&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nd"&gt;@Param&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s"&gt;"countryCode"&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="n"&gt;countryCode&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="nc"&gt;String&lt;/span&gt;&lt;span class="p"&gt;):&lt;/span&gt; &lt;span class="nc"&gt;List&lt;/span&gt;&lt;span class="p"&gt;&amp;lt;&lt;/span&gt;&lt;span class="nc"&gt;CompanySummaryDto&lt;/span&gt;&lt;span class="p"&gt;&amp;gt;&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Trade-offs:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;The fully qualified class name in the JPQL string (&lt;code&gt;new dev.protsenko.jpa.CompanySummaryDto(...)&lt;/code&gt;) is a plain string – the compiler does not validate it. With the default eager repository bootstrap, a wrong class name or mismatched constructor fails at application startup during query validation. Only under &lt;code&gt;BootstrapMode.LAZY&lt;/code&gt; is this deferred to first interaction. IDEs like IntelliJ IDEA can resolve the reference and warn you, but it is not a compile-time guarantee.&lt;/li&gt;
&lt;li&gt;Constructor argument order is not validated by the compiler. The &lt;code&gt;new&lt;/code&gt; expression maps arguments positionally – a same-type positional swap (for example, &lt;code&gt;name&lt;/code&gt; and &lt;code&gt;countryCode&lt;/code&gt; both being &lt;code&gt;String&lt;/code&gt;) passes all validation but silently assigns wrong values to wrong fields. Always keep the JPQL argument list and the constructor parameter list in sync, and cover the mapping with a test that asserts specific field values.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;When to use:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Public API contracts where you need an explicit, stable response model that can evolve independently from the entity (for example, introducing &lt;code&gt;CompanySummaryDtoV2&lt;/code&gt; for a new API version without touching the original).&lt;/li&gt;
&lt;li&gt;Cases where you want the mapping to be explicit and visible in code – for example, when field names don’t match or you need to transform values (like combining &lt;code&gt;firstName&lt;/code&gt; and &lt;code&gt;lastName&lt;/code&gt; into &lt;code&gt;fullName&lt;/code&gt;).&lt;/li&gt;
&lt;/ul&gt;

&lt;h3&gt;
  
  
  Dynamic projection (choose shape at call site)
&lt;/h3&gt;

&lt;p&gt;A dynamic projection lets you reuse one query method and decide the result shape at the call site by passing a &lt;code&gt;Class&amp;lt;T&amp;gt;&lt;/code&gt; parameter. Spring Data JPA detects the &lt;code&gt;Class&amp;lt;T&amp;gt;&lt;/code&gt; argument at startup, and at each invocation reads the actual class value to choose how to transform the result.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight kotlin"&gt;&lt;code&gt;&lt;span class="kd"&gt;interface&lt;/span&gt; &lt;span class="nc"&gt;CompanyRepository&lt;/span&gt; &lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="nc"&gt;JpaRepository&lt;/span&gt;&lt;span class="p"&gt;&amp;lt;&lt;/span&gt;&lt;span class="nc"&gt;Company&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="nc"&gt;UUID&lt;/span&gt;&lt;span class="p"&gt;&amp;gt;&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
    &lt;span class="k"&gt;fun&lt;/span&gt; &lt;span class="p"&gt;&amp;lt;&lt;/span&gt;&lt;span class="nc"&gt;T&lt;/span&gt;&lt;span class="p"&gt;&amp;gt;&lt;/span&gt; &lt;span class="nf"&gt;findByCountryCode&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;countryCode&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="nc"&gt;String&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;type&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="nc"&gt;Class&lt;/span&gt;&lt;span class="p"&gt;&amp;lt;&lt;/span&gt;&lt;span class="nc"&gt;T&lt;/span&gt;&lt;span class="p"&gt;&amp;gt;):&lt;/span&gt; &lt;span class="nc"&gt;List&lt;/span&gt;&lt;span class="p"&gt;&amp;lt;&lt;/span&gt;&lt;span class="nc"&gt;T&lt;/span&gt;&lt;span class="p"&gt;&amp;gt;&lt;/span&gt;
&lt;span class="p"&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;All three shapes work from the same method:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight kotlin"&gt;&lt;code&gt;&lt;span class="c1"&gt;// Interface-based projection - SQL fetches only declared columns&lt;/span&gt;
&lt;span class="kd"&gt;val&lt;/span&gt; &lt;span class="py"&gt;summaries&lt;/span&gt; &lt;span class="p"&gt;=&lt;/span&gt; &lt;span class="n"&gt;repo&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;findByCountryCode&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s"&gt;"DE"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="nc"&gt;CompanySummaryView&lt;/span&gt;&lt;span class="o"&gt;::&lt;/span&gt;&lt;span class="k"&gt;class&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;java&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;

&lt;span class="c1"&gt;// DTO (data class) - selects only DTO constructor properties; no interface proxy&lt;/span&gt;
&lt;span class="kd"&gt;val&lt;/span&gt; &lt;span class="py"&gt;items&lt;/span&gt; &lt;span class="p"&gt;=&lt;/span&gt; &lt;span class="n"&gt;repo&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;findByCountryCode&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s"&gt;"DE"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="nc"&gt;CompanySummaryDto&lt;/span&gt;&lt;span class="o"&gt;::&lt;/span&gt;&lt;span class="k"&gt;class&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;java&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;

&lt;span class="c1"&gt;// Full entity - all columns fetched&lt;/span&gt;
&lt;span class="kd"&gt;val&lt;/span&gt; &lt;span class="py"&gt;entities&lt;/span&gt; &lt;span class="p"&gt;=&lt;/span&gt; &lt;span class="n"&gt;repo&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;findByCountryCode&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s"&gt;"DE"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="nc"&gt;Company&lt;/span&gt;&lt;span class="o"&gt;::&lt;/span&gt;&lt;span class="k"&gt;class&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;java&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Important distinction: both interface and DTO projections reduce SQL columns in derived queries – only the entity shape selects all entity columns. If column reduction matters and the derived query shape is insufficient, use an explicit field-selecting &lt;code&gt;@Query&lt;/code&gt; with an interface or DTO projection.&lt;/p&gt;

&lt;p&gt;The &lt;code&gt;::class.java&lt;/code&gt; syntax is a Java idiom. In Kotlin you can hide it with a reified inline extension:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight kotlin"&gt;&lt;code&gt;&lt;span class="k"&gt;inline&lt;/span&gt; &lt;span class="k"&gt;fun&lt;/span&gt; &lt;span class="p"&gt;&amp;lt;&lt;/span&gt;&lt;span class="k"&gt;reified&lt;/span&gt; &lt;span class="nc"&gt;T&lt;/span&gt;&lt;span class="p"&gt;&amp;gt;&lt;/span&gt; &lt;span class="nc"&gt;CompanyRepository&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;findByCountryCode&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;countryCode&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="nc"&gt;String&lt;/span&gt;&lt;span class="p"&gt;):&lt;/span&gt; &lt;span class="nc"&gt;List&lt;/span&gt;&lt;span class="p"&gt;&amp;lt;&lt;/span&gt;&lt;span class="nc"&gt;T&lt;/span&gt;&lt;span class="p"&gt;&amp;gt;&lt;/span&gt; &lt;span class="p"&gt;=&lt;/span&gt;
    &lt;span class="nf"&gt;findByCountryCode&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;countryCode&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="nc"&gt;T&lt;/span&gt;&lt;span class="o"&gt;::&lt;/span&gt;&lt;span class="k"&gt;class&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;java&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Kotlin note: member functions shadow extension functions when the signatures match. If the repository already declares &lt;code&gt;findByCountryCode(String): List&amp;lt;Company&amp;gt;&lt;/code&gt;, calling &lt;code&gt;repo.findByCountryCode("DE")&lt;/code&gt; without a type argument resolves to the member. Provide an explicit type argument so the compiler picks the reified extension:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight kotlin"&gt;&lt;code&gt;&lt;span class="c1"&gt;// Explicit type argument required - member would otherwise shadow the extension&lt;/span&gt;
&lt;span class="kd"&gt;val&lt;/span&gt; &lt;span class="py"&gt;summaries&lt;/span&gt; &lt;span class="p"&gt;=&lt;/span&gt; &lt;span class="n"&gt;repo&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;findByCountryCode&lt;/span&gt;&lt;span class="p"&gt;&amp;lt;&lt;/span&gt;&lt;span class="nc"&gt;CompanySummaryView&lt;/span&gt;&lt;span class="p"&gt;&amp;gt;(&lt;/span&gt;&lt;span class="s"&gt;"DE"&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
&lt;span class="kd"&gt;val&lt;/span&gt; &lt;span class="py"&gt;entities&lt;/span&gt;  &lt;span class="p"&gt;=&lt;/span&gt; &lt;span class="n"&gt;repo&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;findByCountryCode&lt;/span&gt;&lt;span class="p"&gt;&amp;lt;&lt;/span&gt;&lt;span class="nc"&gt;Company&lt;/span&gt;&lt;span class="p"&gt;&amp;gt;(&lt;/span&gt;&lt;span class="s"&gt;"DE"&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;When to use:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Same filter logic needed by multiple callers that each require a different result shape – for example, a list API (summary projection), a detail API (full entity), and an event publisher (specific fields).&lt;/li&gt;
&lt;li&gt;Internal service utilities or generic base services where the caller decides the shape.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;When not to use:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Public API controllers – prefer explicit return types for stable, documentable contracts.&lt;/li&gt;
&lt;li&gt;Queries with joins, aggregations, or complex logic where different result shapes actually require different SQL – one query cannot serve all shapes efficiently.&lt;/li&gt;
&lt;li&gt;Native queries – dynamic &lt;code&gt;Class&amp;lt;T&amp;gt;&lt;/code&gt; works when native result columns match DTO constructor arguments in order and type. For mismatched or transformed results, use &lt;code&gt;@NativeQuery(resultSetMapping = …)&lt;/code&gt; with &lt;code&gt;@SqlResultSetMapping&lt;/code&gt;.&lt;/li&gt;
&lt;/ul&gt;

&lt;h3&gt;
  
  
  DTO mapping approaches beyond projections
&lt;/h3&gt;

&lt;p&gt;When projections are not enough – for example, when you need to map write requests to entities, combine data from multiple sources, or produce complex nested response shapes – you need a mapper.&lt;/p&gt;

&lt;h4&gt;
  
  
  Handwritten extension functions
&lt;/h4&gt;

&lt;p&gt;The idiomatic Kotlin approach is a plain extension function on the entity. No dependencies, no configuration, full null safety enforced by the compiler, and trivial to debug. This should be your default choice for most Kotlin projects.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight kotlin"&gt;&lt;code&gt;&lt;span class="k"&gt;fun&lt;/span&gt; &lt;span class="nc"&gt;Company&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;toSummaryDto&lt;/span&gt;&lt;span class="p"&gt;()&lt;/span&gt; &lt;span class="p"&gt;=&lt;/span&gt; &lt;span class="nc"&gt;CompanySummaryDto&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;
    &lt;span class="n"&gt;id&lt;/span&gt; &lt;span class="p"&gt;=&lt;/span&gt; &lt;span class="nf"&gt;requireNotNull&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;id&lt;/span&gt;&lt;span class="p"&gt;),&lt;/span&gt;
    &lt;span class="n"&gt;name&lt;/span&gt; &lt;span class="p"&gt;=&lt;/span&gt; &lt;span class="n"&gt;name&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
    &lt;span class="n"&gt;countryCode&lt;/span&gt; &lt;span class="p"&gt;=&lt;/span&gt; &lt;span class="n"&gt;countryCode&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
    &lt;span class="n"&gt;status&lt;/span&gt; &lt;span class="p"&gt;=&lt;/span&gt; &lt;span class="n"&gt;status&lt;/span&gt;
&lt;span class="p"&gt;)&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;For write-path mapping (request → entity), an extension function works the same way:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight kotlin"&gt;&lt;code&gt;&lt;span class="k"&gt;fun&lt;/span&gt; &lt;span class="nc"&gt;CreateCompanyRequest&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;toEntity&lt;/span&gt;&lt;span class="p"&gt;()&lt;/span&gt; &lt;span class="p"&gt;=&lt;/span&gt; &lt;span class="nc"&gt;Company&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;
    &lt;span class="n"&gt;name&lt;/span&gt; &lt;span class="p"&gt;=&lt;/span&gt; &lt;span class="n"&gt;name&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
    &lt;span class="n"&gt;countryCode&lt;/span&gt; &lt;span class="p"&gt;=&lt;/span&gt; &lt;span class="n"&gt;countryCode&lt;/span&gt;
&lt;span class="p"&gt;)&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;If you need Spring injection (for example, when a mapper depends on another service), group mappings in a &lt;code&gt;@Component&lt;/code&gt; class instead:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight kotlin"&gt;&lt;code&gt;&lt;span class="nd"&gt;@Component&lt;/span&gt;
&lt;span class="kd"&gt;class&lt;/span&gt; &lt;span class="nc"&gt;CompanyMapper&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
    &lt;span class="k"&gt;fun&lt;/span&gt; &lt;span class="nf"&gt;toSummaryDto&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;company&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="nc"&gt;Company&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="p"&gt;=&lt;/span&gt; &lt;span class="nc"&gt;CompanySummaryDto&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;
        &lt;span class="n"&gt;id&lt;/span&gt; &lt;span class="p"&gt;=&lt;/span&gt; &lt;span class="nf"&gt;requireNotNull&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;company&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;id&lt;/span&gt;&lt;span class="p"&gt;),&lt;/span&gt;
        &lt;span class="n"&gt;name&lt;/span&gt; &lt;span class="p"&gt;=&lt;/span&gt; &lt;span class="n"&gt;company&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;name&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
        &lt;span class="n"&gt;countryCode&lt;/span&gt; &lt;span class="p"&gt;=&lt;/span&gt; &lt;span class="n"&gt;company&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;countryCode&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
        &lt;span class="n"&gt;status&lt;/span&gt; &lt;span class="p"&gt;=&lt;/span&gt; &lt;span class="n"&gt;company&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;status&lt;/span&gt;
    &lt;span class="p"&gt;)&lt;/span&gt;
&lt;span class="p"&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;When to use:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Recommended default for most Kotlin projects regardless of size.&lt;/li&gt;
&lt;li&gt;When mappings contain non-trivial logic that a code generator cannot express cleanly.&lt;/li&gt;
&lt;li&gt;When you want zero extra dependencies and full compiler-enforced null safety.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;If extension functions produce too much boilerplate in a large codebase, Konvert is the next step.&lt;/p&gt;

&lt;h4&gt;
  
  
  Konvert
&lt;/h4&gt;

&lt;p&gt;Konvert is a compile-time code generator built on KSP (Kotlin Symbol Processing). It generates actual Kotlin extension functions and fully respects Kotlin null safety.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight kotlin"&gt;&lt;code&gt;&lt;span class="nf"&gt;plugins&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
    &lt;span class="nf"&gt;id&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s"&gt;"com.google.devtools.ksp"&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="n"&gt;version&lt;/span&gt; &lt;span class="s"&gt;"2.2.21-2.0.5"&lt;/span&gt; &lt;span class="c1"&gt;// match your Kotlin version&lt;/span&gt;
&lt;span class="p"&gt;}&lt;/span&gt;

&lt;span class="nf"&gt;dependencies&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
    &lt;span class="nf"&gt;implementation&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s"&gt;"io.mcarle:konvert-api:4.4.0"&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
    &lt;span class="nf"&gt;ksp&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s"&gt;"io.mcarle:konvert:4.4.0"&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
&lt;span class="p"&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Annotate the entity with &lt;code&gt;@KonvertTo&lt;/code&gt; and Konvert generates the extension function automatically:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight kotlin"&gt;&lt;code&gt;&lt;span class="nd"&gt;@KonvertTo&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nc"&gt;CompanySummaryDto&lt;/span&gt;&lt;span class="o"&gt;::&lt;/span&gt;&lt;span class="k"&gt;class&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
&lt;span class="kd"&gt;class&lt;/span&gt; &lt;span class="nc"&gt;Company&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="o"&gt;..&lt;/span&gt;&lt;span class="p"&gt;.)&lt;/span&gt;

&lt;span class="c1"&gt;// Generated: Company.toCompanySummaryDto()&lt;/span&gt;
&lt;span class="kd"&gt;val&lt;/span&gt; &lt;span class="py"&gt;dto&lt;/span&gt; &lt;span class="p"&gt;=&lt;/span&gt; &lt;span class="n"&gt;company&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;toCompanySummaryDto&lt;/span&gt;&lt;span class="p"&gt;()&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;When to use:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;When extension functions produce too much boilerplate across many entities and DTOs.&lt;/li&gt;
&lt;li&gt;When starting a new Kotlin project and want a code generator that generates idiomatic Kotlin output.&lt;/li&gt;
&lt;/ul&gt;

&lt;h4&gt;
  
  
  Worth to know: MapStruct
&lt;/h4&gt;

&lt;p&gt;MapStruct is a well-known mapping library in the Java/Spring ecosystem and you will see it in many Spring Boot projects. It generates mapper implementations at compile time from annotated interfaces and has strong IDE support in IntelliJ IDEA.&lt;/p&gt;

&lt;p&gt;However, for Kotlin projects there are two reasons to think twice before adopting it. First, MapStruct is a Java annotation processor, so Kotlin projects commonly run it through kapt. kapt is in maintenance mode, while KSP is the Kotlin-first processing API and the better default for new Kotlin code generators. Second, MapStruct 1.6.x (current stable) processes Kotlin projects by generating Java source files, so Kotlin null safety and data class semantics have historically been weaker in the generated output. MapStruct 1.7.0.Beta1 significantly improves Kotlin data class support via &lt;code&gt;kotlin-metadata-jvm&lt;/code&gt;, but KSP support is not yet available in any stable release.&lt;/p&gt;

&lt;p&gt;If you are maintaining a large Java codebase that is gradually migrating to Kotlin, MapStruct is a reasonable tool to keep. For new Kotlin projects, prefer handwritten extension functions or Konvert.&lt;/p&gt;

&lt;h2&gt;
  
  
  At the end
&lt;/h2&gt;

&lt;p&gt;I hope this article will be helpful to you; it’s one of the largest materials I’ve ever prepared. If you like it, follow me on &lt;a href="https://www.linkedin.com/in/protsenkodev/" rel="noopener noreferrer"&gt;LinkedIn&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;If you have time and are ready to read about a topic other than Spring Boot Data JPA, I highly recommend reading my &lt;a href="https://protsenko.dev/2025/03/24/how-i-made-docker-linter-for-intellij-idea-and-other-jetbrains-ide/" rel="noopener noreferrer"&gt;IntelliJ Plugin: Building Docker Security Analysis Tools&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;This post is part of my &lt;a href="https://protsenko.dev/spring-data-jpa-guide/" rel="noopener noreferrer"&gt;Spring Data JPA guide&lt;/a&gt;. Read next: &lt;a href="https://protsenko.dev/spring-boot-best-practices-that-should-fail-your-build/" rel="noopener noreferrer"&gt;Spring Boot Best Practices That Should Fail Your Build&lt;/a&gt;.&lt;/strong&gt;&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;&lt;strong&gt;Found this useful?&lt;/strong&gt; Follow me on social media to stay updated.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://t.me/protsenko_dev" rel="noopener noreferrer"&gt;Telegram&lt;/a&gt; · &lt;a href="https://www.linkedin.com/in/protsenkodev/" rel="noopener noreferrer"&gt;LinkedIn&lt;/a&gt;&lt;/p&gt;
&lt;/blockquote&gt;

</description>
      <category>kotlin</category>
      <category>springboot</category>
      <category>jpa</category>
      <category>java</category>
    </item>
    <item>
      <title>Hadolint vs Cloud (IaC) Security: Dockerfile linting in IntelliJ IDEA</title>
      <dc:creator>Dmitry Protsenko</dc:creator>
      <pubDate>Tue, 03 Nov 2026 15:00:00 +0000</pubDate>
      <link>https://dev.to/protsenko/hadolint-vs-cloud-iac-security-dockerfile-linting-in-intellij-idea-30dn</link>
      <guid>https://dev.to/protsenko/hadolint-vs-cloud-iac-security-dockerfile-linting-in-intellij-idea-30dn</guid>
      <description>&lt;p&gt;Hadolint is the Dockerfile linter most guides recommend, and it still waves through a &lt;code&gt;latest&lt;/code&gt; tag hidden behind an &lt;code&gt;ARG&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;I know Hadolint well. When I started my own Docker and Kubernetes linter for JetBrains IDEs, I read its rule definitions one by one and then its GitHub issues, because users who take time to report a problem show you what the tool can’t do. That research ended up as the Cloud (IaC) Security plugin, which now covers many of Hadolint’s rules, written in Kotlin on top of the IDE’s own Dockerfile model.&lt;/p&gt;

&lt;p&gt;So this is a biased comparison, and I say it up front. The two tools solve different parts of the job, and many teams need both.&lt;/p&gt;

&lt;h2&gt;
  
  
  What Hadolint is
&lt;/h2&gt;

&lt;p&gt;Hadolint is a command line linter for Dockerfiles, written in Haskell. It parses the Dockerfile into a syntax tree and checks it against rules with DL codes. It also hands every &lt;code&gt;RUN&lt;/code&gt; instruction to ShellCheck, so you get shell warnings (SC codes) on top of the Dockerfile ones.&lt;/p&gt;

&lt;p&gt;Run it:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight shell"&gt;&lt;code&gt;hadolint Dockerfile
docker run &lt;span class="nt"&gt;--rm&lt;/span&gt; &lt;span class="nt"&gt;-i&lt;/span&gt; hadolint/hadolint &amp;lt; Dockerfile
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;A few rules you will meet in the first week:&lt;/p&gt;

&lt;div class="table-wrapper-paragraph"&gt;&lt;table&gt;
&lt;thead&gt;
&lt;tr&gt;
&lt;th&gt;Rule&lt;/th&gt;
&lt;th&gt;What it flags&lt;/th&gt;
&lt;/tr&gt;
&lt;/thead&gt;
&lt;tbody&gt;
&lt;tr&gt;
&lt;td&gt;DL3006&lt;/td&gt;
&lt;td&gt;Image without an explicit tag&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;DL3007&lt;/td&gt;
&lt;td&gt;Image with the &lt;code&gt;latest&lt;/code&gt; tag&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;DL3008&lt;/td&gt;
&lt;td&gt;
&lt;code&gt;apt-get install&lt;/code&gt; without pinned versions&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;DL3015&lt;/td&gt;
&lt;td&gt;
&lt;code&gt;apt-get install&lt;/code&gt; without &lt;code&gt;--no-install-recommends&lt;/code&gt;
&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;DL3027&lt;/td&gt;
&lt;td&gt;
&lt;code&gt;apt&lt;/code&gt; instead of &lt;code&gt;apt-get&lt;/code&gt;
&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;DL3003&lt;/td&gt;
&lt;td&gt;
&lt;code&gt;cd&lt;/code&gt; instead of &lt;code&gt;WORKDIR&lt;/code&gt;
&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;DL3042&lt;/td&gt;
&lt;td&gt;
&lt;code&gt;pip install&lt;/code&gt; without &lt;code&gt;--no-cache-dir&lt;/code&gt;
&lt;/td&gt;
&lt;/tr&gt;
&lt;/tbody&gt;
&lt;/table&gt;&lt;/div&gt;

&lt;p&gt;To silence a rule for one instruction, put a comment above it. For the whole project, list it in a config file:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight shell"&gt;&lt;code&gt;&lt;span class="c"&gt;# hadolint ignore=DL3008&lt;/span&gt;
RUN apt-get update &lt;span class="o"&gt;&amp;amp;&amp;amp;&lt;/span&gt; apt-get &lt;span class="nb"&gt;install&lt;/span&gt; &lt;span class="nt"&gt;-y&lt;/span&gt; &lt;span class="nt"&gt;--no-install-recommends&lt;/span&gt; curl
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;





&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight yaml"&gt;&lt;code&gt;&lt;span class="c1"&gt;# .hadolint.yaml&lt;/span&gt;
&lt;span class="na"&gt;ignored&lt;/span&gt;&lt;span class="pi"&gt;:&lt;/span&gt;
  &lt;span class="pi"&gt;-&lt;/span&gt; &lt;span class="s"&gt;DL3008&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Output formats cover JSON, SARIF, Checkstyle, Code Climate and a few more, so it fits into almost any CI. There is an official GitHub Action too.&lt;/p&gt;

&lt;h2&gt;
  
  
  Where Hadolint stops
&lt;/h2&gt;

&lt;p&gt;&lt;strong&gt;It sees only Dockerfiles.&lt;/strong&gt; Docker Compose files and Kubernetes manifests are out of scope. A privileged pod or a hostPath volume needs a second tool.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;It runs after you write the code.&lt;/strong&gt; Hadolint works on the command line and in CI. In IntelliJ IDEA you can wire it up as an external tool, and the feedback comes only when you run it.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Some gaps stay open.&lt;/strong&gt; When I read the issues, one that stuck with me was variables in &lt;code&gt;FROM&lt;/code&gt;. Hadolint checks the text of the tag, and it doesn’t resolve the &lt;code&gt;ARG&lt;/code&gt; behind it (&lt;a href="https://github.com/hadolint/hadolint/issues/1078" rel="noopener noreferrer"&gt;an open issue&lt;/a&gt; shows the same blind spot):&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight shell"&gt;&lt;code&gt;ARG &lt;span class="nv"&gt;BASE_TAG&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;latest
FROM ubuntu:&lt;span class="nv"&gt;$BASE_TAG&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The image is &lt;code&gt;ubuntu:latest&lt;/code&gt;, but the linter sees a tag and moves on. The project looked close to abandoned when I did my research.&lt;/p&gt;

&lt;h2&gt;
  
  
  What the IntelliJ plugin does differently
&lt;/h2&gt;

&lt;p&gt;The Cloud (IaC) Security plugin runs inside IntelliJ IDEA and the other JetBrains IDEs (PyCharm and WebStorm among them) as a set of inspections. The difference you feel first: the warning shows up on the line while you type, sometimes with a quick fix next to it.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Dockerfiles.&lt;/strong&gt; Base image tags (the variable resolved, so the example above gets flagged), running as root, sudo, package manager caches for apk, dnf, yum, zypper and pip, &lt;code&gt;ADD&lt;/code&gt; instead of &lt;code&gt;COPY&lt;/code&gt;, an exposed SSH port and ports out of range, duplicate CMD, ENTRYPOINT, HEALTHCHECK instructions and stage aliases, secrets in ENV, curl piped to bash.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Docker Compose.&lt;/strong&gt; Image tags, the root user, an exposed SSH port and privileged mode.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Kubernetes manifests.&lt;/strong&gt; Privileged containers, host network, PID and IPC namespaces, &lt;code&gt;hostPath&lt;/code&gt; volumes, host ports, added capabilities, seccomp, AppArmor and SELinux overrides, unsafe sysctls, proc mount, containers that can run as root.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Every rule has a page.&lt;/strong&gt; Each inspection links to an explanation with a bad and a fixed example, for instance &lt;a href="https://protsenko.dev/infrastructure-security/avoid-using-apt/" rel="noopener noreferrer"&gt;apt vs apt-get&lt;/a&gt; or &lt;a href="https://protsenko.dev/infrastructure-security/multiple-healthcheck-defined/" rel="noopener noreferrer"&gt;a single HEALTHCHECK per stage&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;CI.&lt;/strong&gt; The same inspections run in &lt;a href="https://protsenko.dev/analyze-docker-kubernetes-files-with-qodana/" rel="noopener noreferrer"&gt;Qodana&lt;/a&gt;, so the IDE and the pipeline agree on what is a problem.&lt;/p&gt;

&lt;p&gt;What it doesn’t do: it doesn’t run ShellCheck on your &lt;code&gt;RUN&lt;/code&gt; scripts, and it lives in JetBrains IDEs, so a VS Code user won’t get it.&lt;/p&gt;

&lt;h2&gt;
  
  
  Hadolint vs the plugin, side by side
&lt;/h2&gt;

&lt;div class="table-wrapper-paragraph"&gt;&lt;table&gt;
&lt;thead&gt;
&lt;tr&gt;
&lt;th&gt;&lt;/th&gt;
&lt;th&gt;Hadolint&lt;/th&gt;
&lt;th&gt;Cloud (IaC) Security&lt;/th&gt;
&lt;/tr&gt;
&lt;/thead&gt;
&lt;tbody&gt;
&lt;tr&gt;
&lt;td&gt;Where it runs&lt;/td&gt;
&lt;td&gt;CLI, Docker image, CI&lt;/td&gt;
&lt;td&gt;JetBrains IDEs, Qodana in CI&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;When you see a problem&lt;/td&gt;
&lt;td&gt;When you run it&lt;/td&gt;
&lt;td&gt;While you type&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;Dockerfile rules&lt;/td&gt;
&lt;td&gt;Yes, DL codes&lt;/td&gt;
&lt;td&gt;Yes, many Hadolint rules plus Trivy checks&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;Shell checks in &lt;code&gt;RUN&lt;/code&gt;
&lt;/td&gt;
&lt;td&gt;Yes, through ShellCheck&lt;/td&gt;
&lt;td&gt;No&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;Docker Compose files&lt;/td&gt;
&lt;td&gt;No&lt;/td&gt;
&lt;td&gt;Yes&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;Kubernetes manifests&lt;/td&gt;
&lt;td&gt;No&lt;/td&gt;
&lt;td&gt;Yes&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;
&lt;code&gt;ARG&lt;/code&gt; in &lt;code&gt;FROM&lt;/code&gt; resolved&lt;/td&gt;
&lt;td&gt;No&lt;/td&gt;
&lt;td&gt;Yes&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;Quick fixes&lt;/td&gt;
&lt;td&gt;No&lt;/td&gt;
&lt;td&gt;For some rules&lt;/td&gt;
&lt;/tr&gt;
&lt;/tbody&gt;
&lt;/table&gt;&lt;/div&gt;

&lt;h2&gt;
  
  
  Which one to use
&lt;/h2&gt;

&lt;p&gt;If your team works in IntelliJ IDEA, install the plugin for the feedback while you write, and keep Hadolint in CI if you want ShellCheck on your &lt;code&gt;RUN&lt;/code&gt; lines. They don’t fight each other: the plugin’s Dockerfile rules come from Hadolint and Trivy.&lt;/p&gt;

&lt;p&gt;If you edit Dockerfiles in another editor, Hadolint in CI is the minimum. Add a separate scanner for your Kubernetes manifests.&lt;/p&gt;

&lt;p&gt;If you have one Dockerfile and nobody reviews it, either tool beats nothing. Most of the problems both tools catch are small, until the image with &lt;code&gt;latest&lt;/code&gt; and a root user ends up in production.&lt;/p&gt;

&lt;p&gt;Which Dockerfile linter runs in your pipeline today, and did it ever catch something that would have hurt?&lt;/p&gt;

&lt;h2&gt;
  
  
  At the end
&lt;/h2&gt;

&lt;p&gt;If you like this post, follow me on &lt;a href="https://www.linkedin.com/in/protsenkodev/" rel="noopener noreferrer"&gt;LinkedIn&lt;/a&gt; to get new articles about Docker and Kubernetes security. Every rule of the plugin has its own page in &lt;a href="https://protsenko.dev/infrastructure-security/" rel="noopener noreferrer"&gt;Infrastructure security&lt;/a&gt;.&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;&lt;strong&gt;Found this useful?&lt;/strong&gt; Follow me on social media to stay updated.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://t.me/protsenko_dev" rel="noopener noreferrer"&gt;Telegram&lt;/a&gt; · &lt;a href="https://www.linkedin.com/in/protsenkodev/" rel="noopener noreferrer"&gt;LinkedIn&lt;/a&gt;&lt;/p&gt;
&lt;/blockquote&gt;

</description>
      <category>docker</category>
      <category>intellij</category>
      <category>security</category>
      <category>devops</category>
    </item>
    <item>
      <title>Spring Boot Best Practices That Should Fail Your Build</title>
      <dc:creator>Dmitry Protsenko</dc:creator>
      <pubDate>Mon, 02 Nov 2026 15:00:00 +0000</pubDate>
      <link>https://dev.to/protsenko/spring-boot-best-practices-that-should-fail-your-build-24n7</link>
      <guid>https://dev.to/protsenko/spring-boot-best-practices-that-should-fail-your-build-24n7</guid>
      <description>&lt;p&gt;Spring Boot best practices are useless if they live only in code reviews.&lt;/p&gt;

&lt;p&gt;You probably know the story. The team agrees that field injection is bad. Everyone knows that &lt;code&gt;@Transactional&lt;/code&gt; on a private method does not work with Spring proxies. Someone writes in Confluence that controllers should not call repositories directly. Then two months later, the same problems are back in the codebase.&lt;/p&gt;




&lt;p&gt;That is why I created &lt;a href="https://github.com/NordCoderd/spring-boot-code-guard" rel="noopener noreferrer"&gt;Spring Boot Code Guard&lt;/a&gt;. It converts Spring Boot best practices into &lt;a href="https://docs.konsist.lemonappdev.com/" rel="noopener noreferrer"&gt;Konsist&lt;/a&gt; checks that run as regular JUnit 5 tests. The test reads your Kotlin source code, checks annotations, package names, class names, and dependencies, then fails with a rule ID such as &lt;code&gt;CodeGuard:noFieldInjection&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;Let’s break down the rules that should fail your build before they reach code review.&lt;/p&gt;

&lt;h2&gt;
  
  
  Table of contents
&lt;/h2&gt;

&lt;ul&gt;
&lt;li&gt;1. Spring Boot Best Practices Should Be Executable&lt;/li&gt;
&lt;li&gt;
2. General Spring Boot Best Practices

&lt;ul&gt;
&lt;li&gt;Constructor Injection Instead of Field Injection&lt;/li&gt;
&lt;li&gt;Proxy Annotations Must Not Be Placed on Private Methods&lt;/li&gt;
&lt;li&gt;Use Structured Logging Instead of println and printStackTrace()&lt;/li&gt;
&lt;li&gt;Configuration Classes Should Not Store Mutable State&lt;/li&gt;
&lt;li&gt;@Bean Methods Should Live in @Configuration Classes&lt;/li&gt;
&lt;li&gt;Custom Exceptions Should Not Extend Raw Exception&lt;/li&gt;
&lt;li&gt;Kotlin Data Classes Should Not Be JPA Entities&lt;/li&gt;
&lt;li&gt;JPA Entities Should Declare an Identifier&lt;/li&gt;
&lt;li&gt;Repository Methods Should Return Concrete Types&lt;/li&gt;
&lt;li&gt;@Transactional Belongs in the Service Layer&lt;/li&gt;
&lt;li&gt;Domain and Entity Packages Should Not Depend on Spring&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;li&gt;3. Naming Rules&lt;/li&gt;
&lt;li&gt;
4. Spring Boot Project Structure Best Practices

&lt;ul&gt;
&lt;li&gt;Positive Placement Rules&lt;/li&gt;
&lt;li&gt;Exclusive Package Rules&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;li&gt;
5. Spring Boot REST API Best Practices

&lt;ul&gt;
&lt;li&gt;Use Specific HTTP Method Annotations&lt;/li&gt;
&lt;li&gt;Do Not Add Trailing Slashes to Mapping Paths&lt;/li&gt;
&lt;li&gt;GET Endpoints Should Return Something&lt;/li&gt;
&lt;li&gt;Do Not Expose JPA Entities Through REST APIs&lt;/li&gt;
&lt;li&gt;Controllers Should Not Depend on Repositories&lt;/li&gt;
&lt;li&gt;Services Should Not Depend on Web Types&lt;/li&gt;
&lt;li&gt;Services Should Return DTOs, Not Entities&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;li&gt;6. How to Add Code Guard&lt;/li&gt;
&lt;li&gt;7. What This Does Not Replace&lt;/li&gt;
&lt;/ul&gt;

&lt;h2&gt;
  
  
  1. Spring Boot Best Practices Should Be Executable
&lt;/h2&gt;

&lt;p&gt;Spring Boot gives you a lot of freedom. The official documentation even says that Spring Boot does not require a specific code layout, but there are best practices that help, especially around root packages and component scanning (&lt;a href="https://docs.spring.io/spring-boot/reference/using/structuring-your-code.html" rel="noopener noreferrer"&gt;Spring Boot: Structuring Your Code&lt;/a&gt;).&lt;/p&gt;

&lt;p&gt;The reviewer should think about behavior, edge cases, business logic, security, and production risks. Repeating “please move this class to the service package” for the hundredth time is painful to watch.&lt;/p&gt;

&lt;p&gt;Code Guard’s position is simple: if a Spring Boot best practice can be described structurally, it can be tested structurally.&lt;/p&gt;

&lt;h2&gt;
  
  
  2. General Spring Boot Best Practices
&lt;/h2&gt;

&lt;p&gt;General Spring Boot best practices catch the small details that look harmless in a pull request and become annoying when they spread across the project.&lt;/p&gt;

&lt;h3&gt;
  
  
  Constructor Injection Instead of Field Injection
&lt;/h3&gt;

&lt;p&gt;Spring supports field injection with &lt;code&gt;@Autowired&lt;/code&gt;, but it also supports constructor injection, and a single constructor is used even when it is not annotated (&lt;a href="https://docs.spring.io/spring-framework/reference/core/beans/annotation-config/autowired.html" rel="noopener noreferrer"&gt;Spring Framework: Using &lt;code&gt;@Autowired&lt;/code&gt;&lt;/a&gt;).&lt;/p&gt;

&lt;p&gt;Code Guard chooses constructor injection as the project rule:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight kotlin"&gt;&lt;code&gt;&lt;span class="c1"&gt;// Bad&lt;/span&gt;
&lt;span class="nd"&gt;@Service&lt;/span&gt;
&lt;span class="kd"&gt;class&lt;/span&gt; &lt;span class="nc"&gt;PaymentService&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
    &lt;span class="nd"&gt;@Autowired&lt;/span&gt;
    &lt;span class="k"&gt;lateinit&lt;/span&gt; &lt;span class="kd"&gt;var&lt;/span&gt; &lt;span class="py"&gt;repository&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="nc"&gt;PaymentRepository&lt;/span&gt;
&lt;span class="p"&gt;}&lt;/span&gt;
&lt;span class="c1"&gt;// Better&lt;/span&gt;
&lt;span class="nd"&gt;@Service&lt;/span&gt;
&lt;span class="kd"&gt;class&lt;/span&gt; &lt;span class="nc"&gt;PaymentService&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;
    &lt;span class="k"&gt;private&lt;/span&gt; &lt;span class="kd"&gt;val&lt;/span&gt; &lt;span class="py"&gt;repository&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="nc"&gt;PaymentRepository&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
&lt;span class="p"&gt;)&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Rule: &lt;code&gt;CodeGuard:noFieldInjection&lt;/code&gt;&lt;/p&gt;

&lt;p&gt;Why fail the build? Dependencies should be visible from the constructor. If a class has too many dependencies, you see it immediately.&lt;/p&gt;

&lt;h3&gt;
  
  
  Proxy Annotations Must Not Be Placed on Private Methods
&lt;/h3&gt;

&lt;p&gt;Spring AOP proxying has a hard limitation: private methods cannot be advised because they cannot be overridden (&lt;a href="https://docs.spring.io/spring-framework/reference/core/aop/proxying.html" rel="noopener noreferrer"&gt;Spring Framework: Proxying Mechanisms&lt;/a&gt;). The transaction documentation also explains that proxy-based transactions intercept calls coming through the proxy, not internal calls hidden inside the same object (&lt;a href="https://docs.spring.io/spring-framework/reference/data-access/transaction/declarative/annotations.html" rel="noopener noreferrer"&gt;Spring Framework: Using &lt;code&gt;@Transactional&lt;/code&gt;&lt;/a&gt;).&lt;/p&gt;

&lt;p&gt;This code looks meaningful, but the annotation is lying to you:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight kotlin"&gt;&lt;code&gt;&lt;span class="c1"&gt;// Bad&lt;/span&gt;
&lt;span class="nd"&gt;@Service&lt;/span&gt;
&lt;span class="kd"&gt;class&lt;/span&gt; &lt;span class="nc"&gt;InvoiceService&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;

    &lt;span class="k"&gt;fun&lt;/span&gt; &lt;span class="nf"&gt;createInvoice&lt;/span&gt;&lt;span class="p"&gt;()&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
        &lt;span class="nf"&gt;persistInvoice&lt;/span&gt;&lt;span class="p"&gt;()&lt;/span&gt;
    &lt;span class="p"&gt;}&lt;/span&gt;

    &lt;span class="nd"&gt;@Transactional&lt;/span&gt;
    &lt;span class="k"&gt;private&lt;/span&gt; &lt;span class="k"&gt;fun&lt;/span&gt; &lt;span class="nf"&gt;persistInvoice&lt;/span&gt;&lt;span class="p"&gt;()&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
        &lt;span class="c1"&gt;// no transactional proxy interception here&lt;/span&gt;
    &lt;span class="p"&gt;}&lt;/span&gt;
&lt;span class="p"&gt;}&lt;/span&gt;

&lt;span class="c1"&gt;// Better&lt;/span&gt;
&lt;span class="nd"&gt;@Service&lt;/span&gt;
&lt;span class="kd"&gt;class&lt;/span&gt; &lt;span class="nc"&gt;InvoiceService&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;

    &lt;span class="nd"&gt;@Transactional&lt;/span&gt;
    &lt;span class="k"&gt;fun&lt;/span&gt; &lt;span class="nf"&gt;createInvoice&lt;/span&gt;&lt;span class="p"&gt;()&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
        &lt;span class="nf"&gt;persistInvoice&lt;/span&gt;&lt;span class="p"&gt;()&lt;/span&gt;
    &lt;span class="p"&gt;}&lt;/span&gt;

    &lt;span class="k"&gt;private&lt;/span&gt; &lt;span class="k"&gt;fun&lt;/span&gt; &lt;span class="nf"&gt;persistInvoice&lt;/span&gt;&lt;span class="p"&gt;()&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
        &lt;span class="c1"&gt;// transaction is opened on the public service method&lt;/span&gt;
    &lt;span class="p"&gt;}&lt;/span&gt;
&lt;span class="p"&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Rule: &lt;code&gt;CodeGuard:noProxyAnnotationsOnPrivateMethods&lt;/code&gt;&lt;/p&gt;

&lt;p&gt;The rule covers &lt;code&gt;@Transactional&lt;/code&gt;, &lt;code&gt;@Cacheable&lt;/code&gt;, &lt;code&gt;@CacheEvict&lt;/code&gt;, &lt;code&gt;@CachePut&lt;/code&gt;, and &lt;code&gt;@Async&lt;/code&gt;. Same family of problem: a proxy annotation on code that the proxy cannot intercept.&lt;/p&gt;

&lt;h3&gt;
  
  
  Proxy Methods Must Not Self-Invoke Other Proxy Methods
&lt;/h3&gt;

&lt;p&gt;Same root cause as the private-method case, different symptom. When a public proxy-annotated method calls another proxy-annotated method on the same instance, the call goes through&amp;nbsp;&lt;code&gt;this&lt;/code&gt;, not through the Spring-generated proxy. The second annotation is silently ignored (&lt;a href="https://docs.spring.io/spring-framework/reference/core/aop/proxying.html" rel="noopener noreferrer"&gt;Spring Framework: Understanding AOP Proxies&lt;/a&gt;).&lt;/p&gt;

&lt;p&gt;The transactional reference makes the same point about self-invocation bypassing the proxy and skipping any configured advice (&lt;a href="https://docs.spring.io/spring-framework/reference/data-access/transaction/declarative/annotations.html" rel="noopener noreferrer"&gt;Spring Framework: Using&amp;nbsp;&lt;code&gt;@Transactional&lt;/code&gt;&lt;/a&gt;).&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight kotlin"&gt;&lt;code&gt;&lt;span class="c1"&gt;// Bad&lt;/span&gt;
&lt;span class="nd"&gt;@Service&lt;/span&gt;
&lt;span class="kd"&gt;class&lt;/span&gt; &lt;span class="nc"&gt;ReportService&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;

    &lt;span class="nd"&gt;@Transactional&lt;/span&gt;
    &lt;span class="k"&gt;fun&lt;/span&gt; &lt;span class="nf"&gt;generate&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;id&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="nc"&gt;Long&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
        &lt;span class="nf"&gt;archive&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;id&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="c1"&gt;// self-invocation, @Async never fires&lt;/span&gt;
    &lt;span class="p"&gt;}&lt;/span&gt;

    &lt;span class="nd"&gt;@Async&lt;/span&gt;
    &lt;span class="k"&gt;fun&lt;/span&gt; &lt;span class="nf"&gt;archive&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;id&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="nc"&gt;Long&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
        &lt;span class="c1"&gt;// expected to run on a separate thread, but does not&lt;/span&gt;
    &lt;span class="p"&gt;}&lt;/span&gt;
&lt;span class="p"&gt;}&lt;/span&gt;

&lt;span class="c1"&gt;// Better&lt;/span&gt;
&lt;span class="nd"&gt;@Service&lt;/span&gt;
&lt;span class="kd"&gt;class&lt;/span&gt; &lt;span class="nc"&gt;ReportService&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;
    &lt;span class="k"&gt;private&lt;/span&gt; &lt;span class="kd"&gt;val&lt;/span&gt; &lt;span class="py"&gt;archiveService&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="nc"&gt;ArchiveService&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
    &lt;span class="nd"&gt;@Transactional&lt;/span&gt;
    &lt;span class="k"&gt;fun&lt;/span&gt; &lt;span class="nf"&gt;generate&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;id&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="nc"&gt;Long&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
        &lt;span class="n"&gt;archiveService&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;archive&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;id&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
    &lt;span class="p"&gt;}&lt;/span&gt;
&lt;span class="p"&gt;}&lt;/span&gt;

&lt;span class="nd"&gt;@Service&lt;/span&gt;
&lt;span class="kd"&gt;class&lt;/span&gt; &lt;span class="nc"&gt;ArchiveService&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
    &lt;span class="nd"&gt;@Async&lt;/span&gt;
    &lt;span class="k"&gt;fun&lt;/span&gt; &lt;span class="nf"&gt;archive&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;id&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="nc"&gt;Long&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
        &lt;span class="c1"&gt;// proxied call from another bean, advice runs&lt;/span&gt;
    &lt;span class="p"&gt;}&lt;/span&gt;
&lt;span class="p"&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Rule:&amp;nbsp;&lt;code&gt;CodeGuard:noSelfInvocationOfProxyMethods&lt;/code&gt;&lt;/p&gt;

&lt;p&gt;The rule also flags proxy method calls from constructors, init blocks, and property initializers – the proxy is not in place yet during object construction, so even an external-looking call would still bypass it.&lt;/p&gt;

&lt;h3&gt;
  
  
  Use Structured Logging Instead of println and printStackTrace()
&lt;/h3&gt;

&lt;p&gt;Spring Boot has a logging system with Logback as the default when using starters, and it pre-configures log output with levels, logger names, process IDs, and optional file output (&lt;a href="https://docs.spring.io/spring-boot/reference/features/logging.html" rel="noopener noreferrer"&gt;Spring Boot: Logging&lt;/a&gt;).&lt;/p&gt;

&lt;p&gt;This code bypasses it:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight kotlin"&gt;&lt;code&gt;&lt;span class="c1"&gt;// Bad&lt;/span&gt;
&lt;span class="nd"&gt;@Service&lt;/span&gt;
&lt;span class="kd"&gt;class&lt;/span&gt; &lt;span class="nc"&gt;ImportService&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
    &lt;span class="k"&gt;fun&lt;/span&gt; &lt;span class="nf"&gt;importFile&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;file&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="nc"&gt;File&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
        &lt;span class="k"&gt;try&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
            &lt;span class="nf"&gt;println&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s"&gt;"Importing ${file.name}"&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
        &lt;span class="p"&gt;}&lt;/span&gt; &lt;span class="k"&gt;catch&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;ex&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="nc"&gt;IOException&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
            &lt;span class="n"&gt;ex&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;printStackTrace&lt;/span&gt;&lt;span class="p"&gt;()&lt;/span&gt;
        &lt;span class="p"&gt;}&lt;/span&gt;
    &lt;span class="p"&gt;}&lt;/span&gt;
&lt;span class="p"&gt;}&lt;/span&gt;

&lt;span class="c1"&gt;// Better&lt;/span&gt;
&lt;span class="nd"&gt;@Service&lt;/span&gt;
&lt;span class="kd"&gt;class&lt;/span&gt; &lt;span class="nc"&gt;ImportService&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
    &lt;span class="k"&gt;private&lt;/span&gt; &lt;span class="kd"&gt;val&lt;/span&gt; &lt;span class="py"&gt;log&lt;/span&gt; &lt;span class="p"&gt;=&lt;/span&gt; &lt;span class="nc"&gt;LoggerFactory&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;getLogger&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;javaClass&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;

    &lt;span class="k"&gt;fun&lt;/span&gt; &lt;span class="nf"&gt;importFile&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;file&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="nc"&gt;File&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
        &lt;span class="k"&gt;try&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
            &lt;span class="n"&gt;log&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;info&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s"&gt;"Importing {}"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;file&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;name&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
        &lt;span class="p"&gt;}&lt;/span&gt; &lt;span class="k"&gt;catch&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;ex&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="nc"&gt;IOException&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
            &lt;span class="n"&gt;log&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;error&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s"&gt;"Failed to import {}"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;file&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;name&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;ex&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
        &lt;span class="p"&gt;}&lt;/span&gt;
    &lt;span class="p"&gt;}&lt;/span&gt;
&lt;span class="p"&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Rules:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;&lt;code&gt;CodeGuard:loggerInsteadOfPrint&lt;/code&gt;&lt;/li&gt;
&lt;li&gt;&lt;code&gt;CodeGuard:noStackTracePrint&lt;/code&gt;&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;Good practice here is not “never debug locally.” Good practice is not letting local debugging habits become production behavior.&lt;/p&gt;

&lt;h3&gt;
  
  
  Configuration Classes Should Not Store Mutable State
&lt;/h3&gt;

&lt;p&gt;Spring documents &lt;code&gt;@Configuration&lt;/code&gt; classes as sources of bean definitions, with &lt;code&gt;@Bean&lt;/code&gt; methods used to instantiate and configure Spring-managed objects (&lt;a href="https://docs.spring.io/spring-framework/reference/core/beans/java/basic-concepts.html" rel="noopener noreferrer"&gt;Spring Framework: &lt;code&gt;@Bean&lt;/code&gt; and &lt;code&gt;@Configuration&lt;/code&gt;&lt;/a&gt;).&lt;/p&gt;

&lt;p&gt;Code Guard enforces a stricter project rule: &lt;code&gt;@Configuration&lt;/code&gt; classes should define beans, not behave like mutable state holders.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight kotlin"&gt;&lt;code&gt;&lt;span class="c1"&gt;// Bad&lt;/span&gt;
&lt;span class="nd"&gt;@Configuration&lt;/span&gt;
&lt;span class="kd"&gt;class&lt;/span&gt; &lt;span class="nc"&gt;MailConfiguration&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
    &lt;span class="kd"&gt;var&lt;/span&gt; &lt;span class="py"&gt;retries&lt;/span&gt; &lt;span class="p"&gt;=&lt;/span&gt; &lt;span class="mi"&gt;0&lt;/span&gt;

    &lt;span class="nd"&gt;@Bean&lt;/span&gt;
    &lt;span class="k"&gt;fun&lt;/span&gt; &lt;span class="nf"&gt;mailClient&lt;/span&gt;&lt;span class="p"&gt;():&lt;/span&gt; &lt;span class="nc"&gt;MailClient&lt;/span&gt; &lt;span class="p"&gt;=&lt;/span&gt; &lt;span class="nc"&gt;MailClient&lt;/span&gt;&lt;span class="p"&gt;()&lt;/span&gt;
&lt;span class="p"&gt;}&lt;/span&gt;

&lt;span class="c1"&gt;// Better&lt;/span&gt;
&lt;span class="nd"&gt;@Configuration&lt;/span&gt;
&lt;span class="kd"&gt;class&lt;/span&gt; &lt;span class="nc"&gt;MailConfiguration&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
    &lt;span class="nd"&gt;@Bean&lt;/span&gt;
    &lt;span class="k"&gt;fun&lt;/span&gt; &lt;span class="nf"&gt;mailClient&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;properties&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="nc"&gt;MailProperties&lt;/span&gt;&lt;span class="p"&gt;):&lt;/span&gt; &lt;span class="nc"&gt;MailClient&lt;/span&gt; &lt;span class="p"&gt;=&lt;/span&gt;
        &lt;span class="nc"&gt;MailClient&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;properties&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;host&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;properties&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;port&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
&lt;span class="p"&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Rule: &lt;code&gt;CodeGuard:statelessConfiguration&lt;/code&gt;&lt;/p&gt;

&lt;p&gt;There are intentional exceptions for &lt;code&gt;@Value&lt;/code&gt; and &lt;code&gt;@ConfigurationProperties&lt;/code&gt; fields. The rule is not against configuration values. It is against turning configuration classes into stateful objects.&lt;/p&gt;

&lt;h3&gt;
  
  
  &lt;a class="mentioned-user" href="https://dev.to/bean"&gt;@bean&lt;/a&gt; Methods Should Live in @Configuration Classes
&lt;/h3&gt;

&lt;p&gt;Spring allows &lt;code&gt;@Bean&lt;/code&gt; methods in non-&lt;code&gt;@Configuration&lt;/code&gt; classes, but the &lt;code&gt;@Bean&lt;/code&gt; javadoc calls that “lite mode.” In lite mode, inter-bean method calls are plain Java/Kotlin calls and are not intercepted through the CGLIB-enhanced configuration class semantics (&lt;a href="https://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/context/annotation/Bean.html" rel="noopener noreferrer"&gt;Spring Framework &lt;code&gt;@Bean&lt;/code&gt; javadoc&lt;/a&gt;).&lt;/p&gt;

&lt;p&gt;Code Guard chooses the predictable rule:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight kotlin"&gt;&lt;code&gt;&lt;span class="c1"&gt;// Bad&lt;/span&gt;
&lt;span class="nd"&gt;@Component&lt;/span&gt;
&lt;span class="kd"&gt;class&lt;/span&gt; &lt;span class="nc"&gt;ClientFactory&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
    &lt;span class="nd"&gt;@Bean&lt;/span&gt;
    &lt;span class="k"&gt;fun&lt;/span&gt; &lt;span class="nf"&gt;client&lt;/span&gt;&lt;span class="p"&gt;():&lt;/span&gt; &lt;span class="nc"&gt;HttpClient&lt;/span&gt; &lt;span class="p"&gt;=&lt;/span&gt; &lt;span class="nc"&gt;HttpClient&lt;/span&gt;&lt;span class="p"&gt;()&lt;/span&gt;
&lt;span class="p"&gt;}&lt;/span&gt;

&lt;span class="c1"&gt;// Better&lt;/span&gt;
&lt;span class="nd"&gt;@Configuration&lt;/span&gt;
&lt;span class="kd"&gt;class&lt;/span&gt; &lt;span class="nc"&gt;ClientConfiguration&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
    &lt;span class="nd"&gt;@Bean&lt;/span&gt;
    &lt;span class="k"&gt;fun&lt;/span&gt; &lt;span class="nf"&gt;client&lt;/span&gt;&lt;span class="p"&gt;():&lt;/span&gt; &lt;span class="nc"&gt;HttpClient&lt;/span&gt; &lt;span class="p"&gt;=&lt;/span&gt; &lt;span class="nc"&gt;HttpClient&lt;/span&gt;&lt;span class="p"&gt;()&lt;/span&gt;
&lt;span class="p"&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Rule: &lt;code&gt;CodeGuard:beanMethodsInConfiguration&lt;/code&gt;&lt;/p&gt;

&lt;p&gt;Yes, Spring can handle lite mode. No, I don’t want it used accidentally in the codebase.&lt;/p&gt;

&lt;h3&gt;
  
  
  Custom Exceptions Should Not Extend Raw Exception
&lt;/h3&gt;

&lt;p&gt;Checked exceptions have their place, but many Spring Boot applications are cleaner when domain and application exceptions are unchecked and handled by controller advice. Code Guard enforces that classes ending with &lt;code&gt;Exception&lt;/code&gt; extend &lt;code&gt;RuntimeException&lt;/code&gt;, one of the well-known unchecked subtypes, &lt;code&gt;ResponseStatusException&lt;/code&gt;, &lt;code&gt;NestedRuntimeException&lt;/code&gt;, or another custom exception class.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight kotlin"&gt;&lt;code&gt;&lt;span class="c1"&gt;// Bad&lt;/span&gt;
&lt;span class="kd"&gt;class&lt;/span&gt; &lt;span class="nc"&gt;PaymentFailedException&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;message&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="nc"&gt;String&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="nc"&gt;Exception&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;message&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;

&lt;span class="c1"&gt;// Better&lt;/span&gt;
&lt;span class="kd"&gt;class&lt;/span&gt; &lt;span class="nc"&gt;PaymentFailedException&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;message&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="nc"&gt;String&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="nc"&gt;RuntimeException&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;message&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Rule: &lt;code&gt;CodeGuard:customExceptionStructure&lt;/code&gt;&lt;/p&gt;

&lt;p&gt;This is a project convention, not a Spring Framework requirement. The point is consistency. If every service invents its own exception hierarchy, global error handling becomes a mess.&lt;/p&gt;

&lt;h3&gt;
  
  
  Kotlin Data Classes Should Not Be JPA Entities
&lt;/h3&gt;

&lt;p&gt;Kotlin data classes automatically generate equals() and hashCode() from primary constructor properties, and data classes cannot be open (&lt;a href="https://kotlinlang.org/docs/data-classes.html" rel="noopener noreferrer"&gt;Kotlin: Data Classes&lt;/a&gt;). Hibernate explains that final entity classes prevent proxy creation for lazy loading unless you use special alternatives, such as proxying an interface (&lt;a href="https://docs.hibernate.org/orm/6.6/userguide/html_single/" rel="noopener noreferrer"&gt;Hibernate ORM User Guide&lt;/a&gt;).&lt;/p&gt;

&lt;p&gt;That is already enough to be paranoid.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight kotlin"&gt;&lt;code&gt;&lt;span class="c1"&gt;// Bad&lt;/span&gt;
&lt;span class="nd"&gt;@Entity&lt;/span&gt;
&lt;span class="kd"&gt;data class&lt;/span&gt; &lt;span class="nc"&gt;UserEntity&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;
    &lt;span class="nd"&gt;@Id&lt;/span&gt;
    &lt;span class="kd"&gt;val&lt;/span&gt; &lt;span class="py"&gt;id&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="nc"&gt;Long&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
    &lt;span class="kd"&gt;val&lt;/span&gt; &lt;span class="py"&gt;email&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="nc"&gt;String&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
&lt;span class="p"&gt;)&lt;/span&gt;

&lt;span class="c1"&gt;// Better&lt;/span&gt;
&lt;span class="nd"&gt;@Entity&lt;/span&gt;
&lt;span class="kd"&gt;class&lt;/span&gt; &lt;span class="nc"&gt;UserEntity&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;
    &lt;span class="nd"&gt;@Id&lt;/span&gt;
    &lt;span class="kd"&gt;var&lt;/span&gt; &lt;span class="py"&gt;id&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="nc"&gt;Long&lt;/span&gt;&lt;span class="p"&gt;?&lt;/span&gt; &lt;span class="p"&gt;=&lt;/span&gt; &lt;span class="k"&gt;null&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;

    &lt;span class="kd"&gt;var&lt;/span&gt; &lt;span class="py"&gt;email&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="nc"&gt;String&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
&lt;span class="p"&gt;)&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Rule: &lt;code&gt;CodeGuard:noDataClassEntity&lt;/code&gt;&lt;/p&gt;

&lt;p&gt;If you want deeper JPA entity design details, I wrote a separate guide: &lt;a href="https://protsenko.dev/spring-data-jpa-with-kotlin-best-practices-for-spring-boot/" rel="noopener noreferrer"&gt;Spring Data JPA with Kotlin: Entities, Repositories, and Pitfalls&lt;/a&gt;.&lt;/p&gt;

&lt;h3&gt;
  
  
  JPA Entities Should Declare an Identifier
&lt;/h3&gt;

&lt;p&gt;Hibernate’s user guide is direct here: every entity must define an identifier, and simple identifiers use the &lt;code&gt;@Id&lt;/code&gt; annotation (&lt;a href="https://docs.hibernate.org/orm/6.6/userguide/html_single/#identifiers" rel="noopener noreferrer"&gt;Hibernate ORM User Guide: Identifiers&lt;/a&gt;).&lt;/p&gt;

&lt;p&gt;Code Guard checks that an &lt;code&gt;@Entity&lt;/code&gt; class, or one of its parents inside the same codebase, declares an &lt;code&gt;@Id&lt;/code&gt; field.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight kotlin"&gt;&lt;code&gt;&lt;span class="c1"&gt;// Bad&lt;/span&gt;
&lt;span class="nd"&gt;@Entity&lt;/span&gt;
&lt;span class="kd"&gt;class&lt;/span&gt; &lt;span class="nc"&gt;AuditLogEntity&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;
    &lt;span class="kd"&gt;var&lt;/span&gt; &lt;span class="py"&gt;message&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="nc"&gt;String&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
&lt;span class="p"&gt;)&lt;/span&gt;

&lt;span class="c1"&gt;// Better&lt;/span&gt;
&lt;span class="nd"&gt;@Entity&lt;/span&gt;
&lt;span class="kd"&gt;class&lt;/span&gt; &lt;span class="nc"&gt;AuditLogEntity&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;
    &lt;span class="nd"&gt;@Id&lt;/span&gt;
    &lt;span class="kd"&gt;var&lt;/span&gt; &lt;span class="py"&gt;id&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="nc"&gt;Long&lt;/span&gt;&lt;span class="p"&gt;?&lt;/span&gt; &lt;span class="p"&gt;=&lt;/span&gt; &lt;span class="k"&gt;null&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;

    &lt;span class="kd"&gt;var&lt;/span&gt; &lt;span class="py"&gt;message&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="nc"&gt;String&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
&lt;span class="p"&gt;)&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Rule: &lt;code&gt;CodeGuard:entityId&lt;/code&gt;&lt;/p&gt;

&lt;h3&gt;
  
  
  Repository Methods Should Return Concrete Types
&lt;/h3&gt;

&lt;p&gt;Spring Data JPA supports entity, interface, and DTO projections. It uses the declared return type to build the result (&lt;a href="https://docs.spring.io/spring-data/jpa/reference/repositories/projections.html" rel="noopener noreferrer"&gt;Spring Data JPA: Projections&lt;/a&gt;).&lt;/p&gt;

&lt;p&gt;A repository method that returns &lt;code&gt;Any&lt;/code&gt; or &lt;code&gt;Object&lt;/code&gt; throws that contract away. Callers must guess the type or cast it themselves.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight kotlin"&gt;&lt;code&gt;&lt;span class="c1"&gt;// Bad&lt;/span&gt;
&lt;span class="kd"&gt;interface&lt;/span&gt; &lt;span class="nc"&gt;AuditLogRepository&lt;/span&gt; &lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="nc"&gt;JpaRepository&lt;/span&gt;&lt;span class="p"&gt;&amp;lt;&lt;/span&gt;&lt;span class="nc"&gt;AuditLogEntity&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="nc"&gt;Long&lt;/span&gt;&lt;span class="p"&gt;&amp;gt;&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
    &lt;span class="nd"&gt;@Query&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s"&gt;"select a.message from AuditLogEntity a where a.id = :id"&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
    &lt;span class="k"&gt;fun&lt;/span&gt; &lt;span class="nf"&gt;findMessage&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nd"&gt;@Param&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s"&gt;"id"&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="n"&gt;id&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="nc"&gt;Long&lt;/span&gt;&lt;span class="p"&gt;):&lt;/span&gt; &lt;span class="nc"&gt;Any&lt;/span&gt;&lt;span class="p"&gt;?&lt;/span&gt;
&lt;span class="p"&gt;}&lt;/span&gt;

&lt;span class="c1"&gt;// Better&lt;/span&gt;
&lt;span class="kd"&gt;interface&lt;/span&gt; &lt;span class="nc"&gt;AuditLogRepository&lt;/span&gt; &lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="nc"&gt;JpaRepository&lt;/span&gt;&lt;span class="p"&gt;&amp;lt;&lt;/span&gt;&lt;span class="nc"&gt;AuditLogEntity&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="nc"&gt;Long&lt;/span&gt;&lt;span class="p"&gt;&amp;gt;&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
    &lt;span class="nd"&gt;@Query&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s"&gt;"select a.message from AuditLogEntity a where a.id = :id"&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
    &lt;span class="k"&gt;fun&lt;/span&gt; &lt;span class="nf"&gt;findMessage&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nd"&gt;@Param&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s"&gt;"id"&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="n"&gt;id&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="nc"&gt;Long&lt;/span&gt;&lt;span class="p"&gt;):&lt;/span&gt; &lt;span class="nc"&gt;String&lt;/span&gt;&lt;span class="p"&gt;?&lt;/span&gt;
&lt;span class="p"&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Rule: &lt;code&gt;CodeGuard:repositoryReturnType&lt;/code&gt;&lt;/p&gt;

&lt;p&gt;The rule also looks inside wrappers, so &lt;code&gt;List&amp;lt;Any&amp;gt;&lt;/code&gt;, &lt;code&gt;Optional&amp;lt;Any&amp;gt;&lt;/code&gt;, and &lt;code&gt;Page&amp;lt;Any&amp;gt;&lt;/code&gt; fail too. &lt;code&gt;Map&amp;lt;String, Any&amp;gt;&lt;/code&gt; and other multi-argument generic types remain allowed.&lt;/p&gt;

&lt;h3&gt;
  
  
  @Transactional Belongs in the Service Layer
&lt;/h3&gt;

&lt;p&gt;Spring does not force you to put &lt;code&gt;@Transactional&lt;/code&gt; only in services. It gives you the annotation and proxy infrastructure. Your architecture decides the boundary.&lt;/p&gt;

&lt;p&gt;Code Guard’s rule is deliberately stricter: controllers should not own transaction boundaries. They should translate HTTP input into application calls and HTTP output back to the client.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight kotlin"&gt;&lt;code&gt;&lt;span class="c1"&gt;// Bad&lt;/span&gt;
&lt;span class="nd"&gt;@RestController&lt;/span&gt;
&lt;span class="kd"&gt;class&lt;/span&gt; &lt;span class="nc"&gt;OrderController&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;
    &lt;span class="k"&gt;private&lt;/span&gt; &lt;span class="kd"&gt;val&lt;/span&gt; &lt;span class="py"&gt;orderService&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="nc"&gt;OrderService&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
    &lt;span class="nd"&gt;@Transactional&lt;/span&gt;
    &lt;span class="nd"&gt;@PostMapping&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s"&gt;"/orders"&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
    &lt;span class="k"&gt;fun&lt;/span&gt; &lt;span class="nf"&gt;create&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nd"&gt;@RequestBody&lt;/span&gt; &lt;span class="n"&gt;request&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="nc"&gt;CreateOrderRequest&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="p"&gt;=&lt;/span&gt;
        &lt;span class="n"&gt;orderService&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;create&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;request&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
&lt;span class="p"&gt;}&lt;/span&gt;

&lt;span class="c1"&gt;// Better&lt;/span&gt;
&lt;span class="nd"&gt;@Service&lt;/span&gt;
&lt;span class="kd"&gt;class&lt;/span&gt; &lt;span class="nc"&gt;OrderService&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
    &lt;span class="nd"&gt;@Transactional&lt;/span&gt;
    &lt;span class="k"&gt;fun&lt;/span&gt; &lt;span class="nf"&gt;create&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;request&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="nc"&gt;CreateOrderRequest&lt;/span&gt;&lt;span class="p"&gt;):&lt;/span&gt; &lt;span class="nc"&gt;OrderResponse&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
        &lt;span class="c1"&gt;// transactional business operation&lt;/span&gt;
    &lt;span class="p"&gt;}&lt;/span&gt;
&lt;span class="p"&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Rule: &lt;code&gt;CodeGuard:transactionalPlacement&lt;/code&gt;&lt;/p&gt;

&lt;p&gt;I covered more transaction details in &lt;a href="https://protsenko.dev/spring-data-jpa-best-practices-transactions-and-manual-queries/" rel="noopener noreferrer"&gt;Spring Data JPA Best Practices: Transactions and Manual Queries&lt;/a&gt;.&lt;/p&gt;

&lt;h3&gt;
  
  
  Domain and Entity Packages Should Not Depend on Spring
&lt;/h3&gt;

&lt;p&gt;Code Guard also checks that classes in &lt;code&gt;..domain..&lt;/code&gt; or &lt;code&gt;..entity..&lt;/code&gt; packages do not import &lt;code&gt;org.springframework.*&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;Rule: &lt;code&gt;CodeGuard:domainLayerIndependence&lt;/code&gt;&lt;/p&gt;

&lt;p&gt;This one is not about pleasing a framework. It is about keeping the domain model portable and boring. Your entity should not know that the web layer exists. Your domain object should not need Spring to explain what it is.&lt;/p&gt;

&lt;h2&gt;
  
  
  3. Naming Rules
&lt;/h2&gt;

&lt;p&gt;Naming rules are less exciting than transaction bugs, but they remove friction.&lt;/p&gt;

&lt;p&gt;Code Guard checks:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;
&lt;code&gt;CodeGuard:serviceNaming&lt;/code&gt;: &lt;code&gt;@Service&lt;/code&gt; classes end with &lt;code&gt;Service&lt;/code&gt;.&lt;/li&gt;
&lt;li&gt;
&lt;code&gt;CodeGuard:repositoryNaming&lt;/code&gt;: &lt;code&gt;@Repository&lt;/code&gt; classes and interfaces end with &lt;code&gt;Repository&lt;/code&gt;.&lt;/li&gt;
&lt;li&gt;
&lt;code&gt;CodeGuard:controllerNaming&lt;/code&gt;: &lt;code&gt;@Controller&lt;/code&gt; and &lt;code&gt;@RestController&lt;/code&gt; classes end with &lt;code&gt;Controller&lt;/code&gt;.&lt;/li&gt;
&lt;li&gt;
&lt;code&gt;CodeGuard:exceptionHandlerNaming&lt;/code&gt;: &lt;code&gt;@ControllerAdvice&lt;/code&gt; and &lt;code&gt;@RestControllerAdvice&lt;/code&gt; classes end with &lt;code&gt;ExceptionHandler&lt;/code&gt; or &lt;code&gt;Advice&lt;/code&gt;.&lt;/li&gt;
&lt;li&gt;
&lt;code&gt;CodeGuard:configurationPropertiesNaming&lt;/code&gt;: &lt;code&gt;@ConfigurationProperties&lt;/code&gt; classes end with &lt;code&gt;Properties&lt;/code&gt;.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;Example:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight java"&gt;&lt;code&gt;&lt;span class="c1"&gt;// Bad&lt;/span&gt;
&lt;span class="nd"&gt;@Service&lt;/span&gt;
&lt;span class="kd"&gt;class&lt;/span&gt; &lt;span class="nc"&gt;PaymentProcessor&lt;/span&gt;

&lt;span class="c1"&gt;// Better&lt;/span&gt;
&lt;span class="nd"&gt;@Service&lt;/span&gt;
&lt;span class="kd"&gt;class&lt;/span&gt; &lt;span class="nc"&gt;PaymentService&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;This will not save your application on its own, but it saves attention. When a project has 50 services, 10 repositories, and 7 controllers, predictable naming matters.&lt;/p&gt;

&lt;h2&gt;
  
  
  4. Spring Boot Project Structure Best Practices
&lt;/h2&gt;

&lt;p&gt;This is the strongest architecture section.&lt;/p&gt;

&lt;p&gt;Spring Boot recommends a root package above the rest of the application so that component, entity, and configuration property scanning stay within your project, preventing accidental scanning of everything (&lt;a href="https://docs.spring.io/spring-boot/reference/using/structuring-your-code.html" rel="noopener noreferrer"&gt;Spring Boot: Structuring Your Code&lt;/a&gt;).&lt;/p&gt;

&lt;p&gt;Java package names are conventionally lowercase, and Oracle’s Java tutorial explains the convention to avoid conflicts with class and interface names (&lt;a href="https://docs.oracle.com/javase/tutorial/java/package/namingpkgs.html" rel="noopener noreferrer"&gt;Oracle Java Tutorial: Naming a Package&lt;/a&gt;).&lt;/p&gt;

&lt;p&gt;Code Guard builds on top of these conventions with package rules.&lt;/p&gt;

&lt;h3&gt;
  
  
  Positive Placement Rules
&lt;/h3&gt;

&lt;p&gt;These rules say where a type should live:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;
&lt;code&gt;CodeGuard:packageNaming&lt;/code&gt;: package names must be lowercase.&lt;/li&gt;
&lt;li&gt;
&lt;code&gt;CodeGuard:servicePackage&lt;/code&gt;: &lt;code&gt;@Service&lt;/code&gt; classes must live in a &lt;code&gt;..service..&lt;/code&gt; package segment.&lt;/li&gt;
&lt;li&gt;
&lt;code&gt;CodeGuard:controllerPackage&lt;/code&gt;: controllers must live in &lt;code&gt;..controller..&lt;/code&gt; or &lt;code&gt;..web..&lt;/code&gt;.&lt;/li&gt;
&lt;li&gt;
&lt;code&gt;CodeGuard:configurationPackage&lt;/code&gt;: &lt;code&gt;@Configuration&lt;/code&gt; classes must live in &lt;code&gt;..config..&lt;/code&gt; or &lt;code&gt;..configuration..&lt;/code&gt;.&lt;/li&gt;
&lt;li&gt;
&lt;code&gt;CodeGuard:propertiesValidation&lt;/code&gt;: &lt;code&gt;@ConfigurationProperties&lt;/code&gt; classes must live in &lt;code&gt;..property..&lt;/code&gt;.&lt;/li&gt;
&lt;li&gt;
&lt;code&gt;CodeGuard:entityPackage&lt;/code&gt;: &lt;code&gt;@Entity&lt;/code&gt; classes must live in &lt;code&gt;..domain..&lt;/code&gt; or &lt;code&gt;..entity..&lt;/code&gt;.&lt;/li&gt;
&lt;li&gt;
&lt;code&gt;CodeGuard:repositoryPackage&lt;/code&gt;: repositories must live in &lt;code&gt;..repository..&lt;/code&gt;.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;Spring Boot also recommends kebab-case canonical property names for configuration binding, and its documentation says the &lt;code&gt;@ConfigurationProperties&lt;/code&gt; prefix must be kebab case (&lt;a href="https://docs.spring.io/spring-boot/reference/features/external-config.html" rel="noopener noreferrer"&gt;Spring Boot: Externalized Configuration&lt;/a&gt;).&lt;/p&gt;

&lt;p&gt;Code Guard enforces that too:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight java"&gt;&lt;code&gt;&lt;span class="c1"&gt;// Bad&lt;/span&gt;
&lt;span class="nd"&gt;@ConfigurationProperties&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="n"&gt;prefix&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="s"&gt;"mailClient"&lt;/span&gt;&lt;span class="o"&gt;)&lt;/span&gt;
&lt;span class="kd"&gt;class&lt;/span&gt; &lt;span class="nc"&gt;MailProperties&lt;/span&gt;

&lt;span class="c1"&gt;// Better&lt;/span&gt;
&lt;span class="nd"&gt;@ConfigurationProperties&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="n"&gt;prefix&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="s"&gt;"mail.client"&lt;/span&gt;&lt;span class="o"&gt;)&lt;/span&gt;
&lt;span class="kd"&gt;class&lt;/span&gt; &lt;span class="nc"&gt;MailProperties&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Rule: &lt;code&gt;CodeGuard:configurationPropertiesPrefixKebabCase&lt;/code&gt;&lt;/p&gt;

&lt;h3&gt;
  
  
  Exclusive Package Rules
&lt;/h3&gt;

&lt;p&gt;If a service must be in a service package, then a repository should not quietly move into the same package.&lt;/p&gt;

&lt;p&gt;Code Guard checks package exclusivity:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;&lt;code&gt;CodeGuard:onlyServicesInServicePackage&lt;/code&gt;&lt;/li&gt;
&lt;li&gt;&lt;code&gt;CodeGuard:onlyEntitiesInEntityPackage&lt;/code&gt;&lt;/li&gt;
&lt;li&gt;&lt;code&gt;CodeGuard:onlyControllersInControllerPackage&lt;/code&gt;&lt;/li&gt;
&lt;li&gt;&lt;code&gt;CodeGuard:onlyConfigurationsInConfigPackage&lt;/code&gt;&lt;/li&gt;
&lt;li&gt;&lt;code&gt;CodeGuard:onlyPropertiesInPropertyPackage&lt;/code&gt;&lt;/li&gt;
&lt;li&gt;&lt;code&gt;CodeGuard:onlyRepositoriesInRepositoryPackage&lt;/code&gt;&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;The rules include practical exceptions for file-level helpers, nested helper classes, and JPA @MappedSuperclass, JPA &lt;a class="mentioned-user" href="https://dev.to/embeddable"&gt;@embeddable&lt;/a&gt;, and @IdClass support where relevant. The goal is not to punish normal Kotlin code organization. The goal is to stop architectural erosion.&lt;/p&gt;

&lt;h2&gt;
  
  
  5. Spring Boot REST API Best Practices
&lt;/h2&gt;

&lt;p&gt;The web layer is where small shortcuts become public API problems.&lt;/p&gt;

&lt;h3&gt;
  
  
  Use Specific HTTP Method Annotations
&lt;/h3&gt;

&lt;p&gt;Spring MVC documents &lt;code&gt;@GetMapping&lt;/code&gt;, &lt;code&gt;@PostMapping&lt;/code&gt;, &lt;code&gt;@PutMapping&lt;/code&gt;, &lt;code&gt;@DeleteMapping&lt;/code&gt;, and &lt;code&gt;@PatchMapping&lt;/code&gt; as shortcut variants of &lt;code&gt;@RequestMapping&lt;/code&gt;, and says most controller methods should be mapped to a specific HTTP method (&lt;a href="https://docs.spring.io/spring-framework/reference/web/webmvc/mvc-controller/ann-requestmapping.html" rel="noopener noreferrer"&gt;Spring Framework: Mapping Requests&lt;/a&gt;).&lt;/p&gt;

&lt;p&gt;Code Guard turns that into a rule:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight kotlin"&gt;&lt;code&gt;&lt;span class="c1"&gt;// Bad&lt;/span&gt;
&lt;span class="nd"&gt;@RestController&lt;/span&gt;
&lt;span class="kd"&gt;class&lt;/span&gt; &lt;span class="nc"&gt;UserController&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
    &lt;span class="nd"&gt;@RequestMapping&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s"&gt;"/users"&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
    &lt;span class="k"&gt;fun&lt;/span&gt; &lt;span class="nf"&gt;users&lt;/span&gt;&lt;span class="p"&gt;():&lt;/span&gt; &lt;span class="nc"&gt;List&lt;/span&gt;&lt;span class="p"&gt;&amp;lt;&lt;/span&gt;&lt;span class="nc"&gt;UserDto&lt;/span&gt;&lt;span class="p"&gt;&amp;gt;&lt;/span&gt; &lt;span class="p"&gt;=&lt;/span&gt; &lt;span class="nf"&gt;emptyList&lt;/span&gt;&lt;span class="p"&gt;()&lt;/span&gt;
&lt;span class="p"&gt;}&lt;/span&gt;

&lt;span class="c1"&gt;// Better&lt;/span&gt;
&lt;span class="nd"&gt;@RestController&lt;/span&gt;
&lt;span class="kd"&gt;class&lt;/span&gt; &lt;span class="nc"&gt;UserController&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
    &lt;span class="nd"&gt;@GetMapping&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s"&gt;"/users"&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
    &lt;span class="k"&gt;fun&lt;/span&gt; &lt;span class="nf"&gt;users&lt;/span&gt;&lt;span class="p"&gt;():&lt;/span&gt; &lt;span class="nc"&gt;List&lt;/span&gt;&lt;span class="p"&gt;&amp;lt;&lt;/span&gt;&lt;span class="nc"&gt;UserDto&lt;/span&gt;&lt;span class="p"&gt;&amp;gt;&lt;/span&gt; &lt;span class="p"&gt;=&lt;/span&gt; &lt;span class="nf"&gt;emptyList&lt;/span&gt;&lt;span class="p"&gt;()&lt;/span&gt;
&lt;span class="p"&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Rule: &lt;code&gt;CodeGuard:httpMethodAnnotation&lt;/code&gt;&lt;/p&gt;

&lt;h3&gt;
  
  
  Do Not Add Trailing Slashes to Mapping Paths
&lt;/h3&gt;

&lt;p&gt;Spring Framework 6 deprecated transparent trailing slash matching and favors explicit redirects through a proxy, servlet/web filter, or controller (&lt;a href="https://docs.spring.io/spring-framework/docs/6.1.21/javadoc-api/org/springframework/web/util/pattern/PathPatternParser.html" rel="noopener noreferrer"&gt;Spring &lt;code&gt;PathPatternParser&lt;/code&gt; javadoc&lt;/a&gt;).&lt;/p&gt;

&lt;p&gt;Code Guard keeps URL mappings consistent:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight kotlin"&gt;&lt;code&gt;&lt;span class="c1"&gt;// Bad&lt;/span&gt;
&lt;span class="nd"&gt;@GetMapping&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s"&gt;"/users/"&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
&lt;span class="k"&gt;fun&lt;/span&gt; &lt;span class="nf"&gt;users&lt;/span&gt;&lt;span class="p"&gt;():&lt;/span&gt; &lt;span class="nc"&gt;List&lt;/span&gt;&lt;span class="p"&gt;&amp;lt;&lt;/span&gt;&lt;span class="nc"&gt;UserDto&lt;/span&gt;&lt;span class="p"&gt;&amp;gt;&lt;/span&gt; &lt;span class="p"&gt;=&lt;/span&gt; &lt;span class="nf"&gt;emptyList&lt;/span&gt;&lt;span class="p"&gt;()&lt;/span&gt;

&lt;span class="c1"&gt;// Better&lt;/span&gt;
&lt;span class="nd"&gt;@GetMapping&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s"&gt;"/users"&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
&lt;span class="k"&gt;fun&lt;/span&gt; &lt;span class="nf"&gt;users&lt;/span&gt;&lt;span class="p"&gt;():&lt;/span&gt; &lt;span class="nc"&gt;List&lt;/span&gt;&lt;span class="p"&gt;&amp;lt;&lt;/span&gt;&lt;span class="nc"&gt;UserDto&lt;/span&gt;&lt;span class="p"&gt;&amp;gt;&lt;/span&gt; &lt;span class="p"&gt;=&lt;/span&gt; &lt;span class="nf"&gt;emptyList&lt;/span&gt;&lt;span class="p"&gt;()&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Rule: &lt;code&gt;CodeGuard:noTrailingSlash&lt;/code&gt;&lt;/p&gt;

&lt;h3&gt;
  
  
  GET Endpoints Should Return Something
&lt;/h3&gt;

&lt;p&gt;A &lt;code&gt;GET&lt;/code&gt; endpoint that returns &lt;code&gt;Unit&lt;/code&gt; or &lt;code&gt;void&lt;/code&gt; is suspicious. If the endpoint is a command, it probably should not be &lt;code&gt;GET&lt;/code&gt;. If it is a query, it should return a meaningful response.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight kotlin"&gt;&lt;code&gt;&lt;span class="c1"&gt;// Bad&lt;/span&gt;
&lt;span class="nd"&gt;@GetMapping&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s"&gt;"/reports/rebuild"&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
&lt;span class="k"&gt;fun&lt;/span&gt; &lt;span class="nf"&gt;rebuildReport&lt;/span&gt;&lt;span class="p"&gt;()&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
    &lt;span class="n"&gt;reportService&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;rebuild&lt;/span&gt;&lt;span class="p"&gt;()&lt;/span&gt;
&lt;span class="p"&gt;}&lt;/span&gt;

&lt;span class="c1"&gt;// Better&lt;/span&gt;
&lt;span class="nd"&gt;@PostMapping&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s"&gt;"/reports/rebuild"&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
&lt;span class="k"&gt;fun&lt;/span&gt; &lt;span class="nf"&gt;rebuildReport&lt;/span&gt;&lt;span class="p"&gt;():&lt;/span&gt; &lt;span class="nc"&gt;RebuildReportResponse&lt;/span&gt; &lt;span class="p"&gt;=&lt;/span&gt;
    &lt;span class="n"&gt;reportService&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;rebuild&lt;/span&gt;&lt;span class="p"&gt;()&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Rule: &lt;code&gt;CodeGuard:restControllerReturnType&lt;/code&gt;&lt;/p&gt;

&lt;h3&gt;
  
  
  Do Not Expose JPA Entities Through REST APIs
&lt;/h3&gt;

&lt;p&gt;Returning entities from controllers couples your HTTP contract to your persistence model. It also makes it easier to accidentally expose fields that were added for database logic, not for clients.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight kotlin"&gt;&lt;code&gt;&lt;span class="c1"&gt;// Bad&lt;/span&gt;
&lt;span class="nd"&gt;@GetMapping&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s"&gt;"/users/{id}"&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
&lt;span class="k"&gt;fun&lt;/span&gt; &lt;span class="nf"&gt;user&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nd"&gt;@PathVariable&lt;/span&gt; &lt;span class="n"&gt;id&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="nc"&gt;Long&lt;/span&gt;&lt;span class="p"&gt;):&lt;/span&gt; &lt;span class="nc"&gt;UserEntity&lt;/span&gt; &lt;span class="p"&gt;=&lt;/span&gt;
    &lt;span class="n"&gt;userService&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;getEntity&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;id&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;

&lt;span class="c1"&gt;// Better&lt;/span&gt;
&lt;span class="nd"&gt;@GetMapping&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s"&gt;"/users/{id}"&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
&lt;span class="k"&gt;fun&lt;/span&gt; &lt;span class="nf"&gt;user&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nd"&gt;@PathVariable&lt;/span&gt; &lt;span class="n"&gt;id&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="nc"&gt;Long&lt;/span&gt;&lt;span class="p"&gt;):&lt;/span&gt; &lt;span class="nc"&gt;UserResponse&lt;/span&gt; &lt;span class="p"&gt;=&lt;/span&gt;
    &lt;span class="n"&gt;userService&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="k"&gt;get&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;id&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Rule: &lt;code&gt;CodeGuard:dtoSeparation&lt;/code&gt;&lt;/p&gt;

&lt;p&gt;Related reading: &lt;a href="https://protsenko.dev/spring-data-jpa-best-practices-repositories-design-guide/" rel="noopener noreferrer"&gt;Spring Data JPA Best Practices: Repositories Design Guide&lt;/a&gt; and &lt;a href="https://protsenko.dev/spring-data-jpa-with-kotlin-best-practices-for-spring-boot/" rel="noopener noreferrer"&gt;Spring Data JPA with Kotlin&lt;/a&gt;.&lt;/p&gt;

&lt;h3&gt;
  
  
  Controllers Should Not Depend on Repositories
&lt;/h3&gt;

&lt;p&gt;Controllers should call services. Services coordinate business logic and data access. Repositories should not appear as constructor parameters in controllers.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight kotlin"&gt;&lt;code&gt;&lt;span class="c1"&gt;// Bad&lt;/span&gt;
&lt;span class="nd"&gt;@RestController&lt;/span&gt;
&lt;span class="kd"&gt;class&lt;/span&gt; &lt;span class="nc"&gt;UserController&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;
    &lt;span class="k"&gt;private&lt;/span&gt; &lt;span class="kd"&gt;val&lt;/span&gt; &lt;span class="py"&gt;userRepository&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="nc"&gt;UserRepository&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
&lt;span class="p"&gt;)&lt;/span&gt;

&lt;span class="c1"&gt;// Better&lt;/span&gt;
&lt;span class="nd"&gt;@RestController&lt;/span&gt;
&lt;span class="kd"&gt;class&lt;/span&gt; &lt;span class="nc"&gt;UserController&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;
    &lt;span class="k"&gt;private&lt;/span&gt; &lt;span class="kd"&gt;val&lt;/span&gt; &lt;span class="py"&gt;userService&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="nc"&gt;UserService&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
&lt;span class="p"&gt;)&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Rule: &lt;code&gt;CodeGuard:controllerRepository&lt;/code&gt;&lt;/p&gt;

&lt;h3&gt;
  
  
  Services Should Not Depend on Web Types
&lt;/h3&gt;

&lt;p&gt;An &lt;code&gt;@Service&lt;/code&gt; should model application work, not HTTP transport. Returning &lt;code&gt;ResponseEntity&lt;/code&gt;, reading &lt;code&gt;HttpServletRequest&lt;/code&gt;, or depending on a controller binds the service to the web layer.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight kotlin"&gt;&lt;code&gt;&lt;span class="c1"&gt;// Bad&lt;/span&gt;
&lt;span class="nd"&gt;@Service&lt;/span&gt;
&lt;span class="kd"&gt;class&lt;/span&gt; &lt;span class="nc"&gt;InvoiceService&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
    &lt;span class="k"&gt;fun&lt;/span&gt; &lt;span class="nf"&gt;find&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;id&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="nc"&gt;Long&lt;/span&gt;&lt;span class="p"&gt;):&lt;/span&gt; &lt;span class="nc"&gt;ResponseEntity&lt;/span&gt;&lt;span class="p"&gt;&amp;lt;&lt;/span&gt;&lt;span class="nc"&gt;InvoiceResponse&lt;/span&gt;&lt;span class="p"&gt;&amp;gt;&lt;/span&gt; &lt;span class="p"&gt;=&lt;/span&gt;
        &lt;span class="nc"&gt;ResponseEntity&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;ok&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nf"&gt;loadInvoice&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;id&lt;/span&gt;&lt;span class="p"&gt;))&lt;/span&gt;
&lt;span class="p"&gt;}&lt;/span&gt;

&lt;span class="c1"&gt;// Better&lt;/span&gt;
&lt;span class="nd"&gt;@Service&lt;/span&gt;
&lt;span class="kd"&gt;class&lt;/span&gt; &lt;span class="nc"&gt;InvoiceService&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
    &lt;span class="k"&gt;fun&lt;/span&gt; &lt;span class="nf"&gt;find&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;id&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="nc"&gt;Long&lt;/span&gt;&lt;span class="p"&gt;):&lt;/span&gt; &lt;span class="nc"&gt;InvoiceResponse&lt;/span&gt; &lt;span class="p"&gt;=&lt;/span&gt;
        &lt;span class="nf"&gt;loadInvoice&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;id&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
&lt;span class="p"&gt;}&lt;/span&gt;

&lt;span class="nd"&gt;@RestController&lt;/span&gt;
&lt;span class="kd"&gt;class&lt;/span&gt; &lt;span class="nc"&gt;InvoiceController&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;
    &lt;span class="k"&gt;private&lt;/span&gt; &lt;span class="kd"&gt;val&lt;/span&gt; &lt;span class="py"&gt;invoiceService&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="nc"&gt;InvoiceService&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
    &lt;span class="nd"&gt;@GetMapping&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s"&gt;"/invoices/{id}"&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
    &lt;span class="k"&gt;fun&lt;/span&gt; &lt;span class="nf"&gt;find&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nd"&gt;@PathVariable&lt;/span&gt; &lt;span class="n"&gt;id&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="nc"&gt;Long&lt;/span&gt;&lt;span class="p"&gt;):&lt;/span&gt; &lt;span class="nc"&gt;ResponseEntity&lt;/span&gt;&lt;span class="p"&gt;&amp;lt;&lt;/span&gt;&lt;span class="nc"&gt;InvoiceResponse&lt;/span&gt;&lt;span class="p"&gt;&amp;gt;&lt;/span&gt; &lt;span class="p"&gt;=&lt;/span&gt;
        &lt;span class="nc"&gt;ResponseEntity&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;ok&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;invoiceService&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;find&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;id&lt;/span&gt;&lt;span class="p"&gt;))&lt;/span&gt;
&lt;span class="p"&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Rule: &lt;code&gt;CodeGuard:serviceWebDependency&lt;/code&gt;&lt;/p&gt;

&lt;p&gt;The rule covers Spring Web and HTTP types, the Jakarta and Javax Servlet APIs, and dependencies on controllers from the same project.&lt;/p&gt;

&lt;h3&gt;
  
  
  Services Should Return DTOs, Not Entities
&lt;/h3&gt;

&lt;p&gt;&lt;code&gt;CodeGuard:dtoSeparation&lt;/code&gt; stops REST controllers from accepting or returning JPA entities. This rule catches the leak one layer earlier: public &lt;code&gt;@Service&lt;/code&gt; methods must not return entities.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight kotlin"&gt;&lt;code&gt;&lt;span class="c1"&gt;// Bad&lt;/span&gt;
&lt;span class="nd"&gt;@Service&lt;/span&gt;
&lt;span class="kd"&gt;class&lt;/span&gt; &lt;span class="nc"&gt;UserService&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;
    &lt;span class="k"&gt;private&lt;/span&gt; &lt;span class="kd"&gt;val&lt;/span&gt; &lt;span class="py"&gt;userRepository&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="nc"&gt;UserRepository&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
    &lt;span class="k"&gt;fun&lt;/span&gt; &lt;span class="nf"&gt;find&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;id&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="nc"&gt;Long&lt;/span&gt;&lt;span class="p"&gt;):&lt;/span&gt; &lt;span class="nc"&gt;UserEntity&lt;/span&gt; &lt;span class="p"&gt;=&lt;/span&gt;
        &lt;span class="n"&gt;userRepository&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;getReferenceById&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;id&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
&lt;span class="p"&gt;}&lt;/span&gt;

&lt;span class="c1"&gt;// Better&lt;/span&gt;
&lt;span class="nd"&gt;@Service&lt;/span&gt;
&lt;span class="kd"&gt;class&lt;/span&gt; &lt;span class="nc"&gt;UserService&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;
    &lt;span class="k"&gt;private&lt;/span&gt; &lt;span class="kd"&gt;val&lt;/span&gt; &lt;span class="py"&gt;userRepository&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="nc"&gt;UserRepository&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
    &lt;span class="k"&gt;fun&lt;/span&gt; &lt;span class="nf"&gt;find&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;id&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="nc"&gt;Long&lt;/span&gt;&lt;span class="p"&gt;):&lt;/span&gt; &lt;span class="nc"&gt;UserResponse&lt;/span&gt; &lt;span class="p"&gt;=&lt;/span&gt;
        &lt;span class="n"&gt;userRepository&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;getReferenceById&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;id&lt;/span&gt;&lt;span class="p"&gt;).&lt;/span&gt;&lt;span class="nf"&gt;toResponse&lt;/span&gt;&lt;span class="p"&gt;()&lt;/span&gt;
&lt;span class="p"&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Rule: &lt;code&gt;CodeGuard:serviceEntityReturn&lt;/code&gt;&lt;/p&gt;

&lt;p&gt;The rule follows common wrappers, so &lt;code&gt;List&amp;lt;UserEntity&amp;gt;&lt;/code&gt;, &lt;code&gt;Optional&amp;lt;UserEntity&amp;gt;&lt;/code&gt;, and &lt;code&gt;Page&amp;lt;UserEntity&amp;gt;&lt;/code&gt; fail too.&lt;/p&gt;

&lt;h2&gt;
  
  
  6. How to Add Code Guard
&lt;/h2&gt;

&lt;p&gt;The library is published to Maven Central, and the README shows this dependency:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight gradle"&gt;&lt;code&gt;&lt;span class="n"&gt;implementation&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="s2"&gt;"dev.protsenko:spring-boot-code-guard:1.0.11"&lt;/span&gt;&lt;span class="o"&gt;)&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Then add a JUnit 5 test, for example &lt;code&gt;src/test/kotlin/SpringCodeGuardTest.kt&lt;/code&gt;:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight kotlin"&gt;&lt;code&gt;&lt;span class="k"&gt;import&lt;/span&gt; &lt;span class="nn"&gt;dev.protsenko.codeguard.spring.springBootRules&lt;/span&gt;
&lt;span class="k"&gt;import&lt;/span&gt; &lt;span class="nn"&gt;org.junit.jupiter.api.Test&lt;/span&gt;

&lt;span class="kd"&gt;class&lt;/span&gt; &lt;span class="nc"&gt;SpringCodeGuardTest&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;

    &lt;span class="nd"&gt;@Test&lt;/span&gt;
    &lt;span class="k"&gt;fun&lt;/span&gt; &lt;span class="nf"&gt;`spring&lt;/span&gt; &lt;span class="n"&gt;boot&lt;/span&gt; &lt;span class="nf"&gt;rules`&lt;/span&gt;&lt;span class="p"&gt;()&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
        &lt;span class="nf"&gt;springBootRules&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
            &lt;span class="nf"&gt;all&lt;/span&gt;&lt;span class="p"&gt;()&lt;/span&gt;
        &lt;span class="p"&gt;}.&lt;/span&gt;&lt;span class="nf"&gt;verify&lt;/span&gt;&lt;span class="p"&gt;()&lt;/span&gt;
    &lt;span class="p"&gt;}&lt;/span&gt;
&lt;span class="p"&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;That is the aggressive mode.&lt;/p&gt;

&lt;p&gt;For a legacy project, start smaller:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight kotlin"&gt;&lt;code&gt;&lt;span class="k"&gt;import&lt;/span&gt; &lt;span class="nn"&gt;dev.protsenko.codeguard.spring.springBootRules&lt;/span&gt;
&lt;span class="k"&gt;import&lt;/span&gt; &lt;span class="nn"&gt;org.junit.jupiter.api.Test&lt;/span&gt;

&lt;span class="kd"&gt;class&lt;/span&gt; &lt;span class="nc"&gt;SpringCodeGuardTest&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;

    &lt;span class="nd"&gt;@Test&lt;/span&gt;
    &lt;span class="k"&gt;fun&lt;/span&gt; &lt;span class="nf"&gt;`spring&lt;/span&gt; &lt;span class="n"&gt;boot&lt;/span&gt; &lt;span class="nf"&gt;rules`&lt;/span&gt;&lt;span class="p"&gt;()&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
        &lt;span class="nf"&gt;springBootRules&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
            &lt;span class="nf"&gt;general&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
                &lt;span class="nf"&gt;noFieldInjection&lt;/span&gt;&lt;span class="p"&gt;()&lt;/span&gt;
            &lt;span class="p"&gt;}&lt;/span&gt;
            &lt;span class="nf"&gt;jpa&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
                &lt;span class="nf"&gt;entitiesHaveIdField&lt;/span&gt;&lt;span class="p"&gt;()&lt;/span&gt;
            &lt;span class="p"&gt;}&lt;/span&gt;
            &lt;span class="nf"&gt;naming&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
                &lt;span class="nf"&gt;serviceNamingConvention&lt;/span&gt;&lt;span class="p"&gt;()&lt;/span&gt;
            &lt;span class="p"&gt;}&lt;/span&gt;
            &lt;span class="nf"&gt;packages&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
                &lt;span class="nf"&gt;packageNamingConvention&lt;/span&gt;&lt;span class="p"&gt;()&lt;/span&gt;
            &lt;span class="p"&gt;}&lt;/span&gt;
            &lt;span class="nf"&gt;web&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
                &lt;span class="nf"&gt;properHttpMethodAnnotations&lt;/span&gt;&lt;span class="p"&gt;()&lt;/span&gt;
            &lt;span class="p"&gt;}&lt;/span&gt;
        &lt;span class="p"&gt;}.&lt;/span&gt;&lt;span class="nf"&gt;verify&lt;/span&gt;&lt;span class="p"&gt;()&lt;/span&gt;
    &lt;span class="p"&gt;}&lt;/span&gt;
&lt;span class="p"&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;If a rule is right but one old class needs time, suppress it explicitly:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight kotlin"&gt;&lt;code&gt;&lt;span class="nd"&gt;@Suppress&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s"&gt;"CodeGuard:noFieldInjection"&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
&lt;span class="nd"&gt;@Service&lt;/span&gt;
&lt;span class="kd"&gt;class&lt;/span&gt; &lt;span class="nc"&gt;LegacyPaymentService&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
    &lt;span class="nd"&gt;@Autowired&lt;/span&gt;
    &lt;span class="k"&gt;lateinit&lt;/span&gt; &lt;span class="kd"&gt;var&lt;/span&gt; &lt;span class="py"&gt;repository&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="nc"&gt;PaymentRepository&lt;/span&gt;
&lt;span class="p"&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;If a rule does not fit your project, exclude it:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight groovy"&gt;&lt;code&gt;&lt;span class="n"&gt;springBootRules&lt;/span&gt; &lt;span class="o"&gt;{&lt;/span&gt;
    &lt;span class="n"&gt;all&lt;/span&gt;&lt;span class="o"&gt;()&lt;/span&gt;
    &lt;span class="n"&gt;exclude&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;
        &lt;span class="s2"&gt;"CodeGuard:noFieldInjection"&lt;/span&gt;&lt;span class="o"&gt;,&lt;/span&gt;
        &lt;span class="s2"&gt;"CodeGuard:transactionalPlacement"&lt;/span&gt;&lt;span class="o"&gt;,&lt;/span&gt;
    &lt;span class="o"&gt;)&lt;/span&gt;
&lt;span class="o"&gt;}.&lt;/span&gt;&lt;span class="na"&gt;verify&lt;/span&gt;&lt;span class="o"&gt;()&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The point is not to turn every team into my team. The point is to make Spring Boot best practices visible, executable, and impossible to forget silently.&lt;/p&gt;

&lt;h2&gt;
  
  
  7. What This Does Not Replace
&lt;/h2&gt;

&lt;p&gt;Code Guard is not a replacement for code review. It is not a full architecture test suite. It will not tell you if your business rule is wrong, your SQL is slow, your transaction boundary is too wide, or your API design is confusing.&lt;/p&gt;

&lt;p&gt;It catches repeatable mistakes before review:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;Wrong annotation placement.&lt;/li&gt;
&lt;li&gt;Wrong package boundaries.&lt;/li&gt;
&lt;li&gt;Wrong naming conventions.&lt;/li&gt;
&lt;li&gt;Entity leaks through REST.&lt;/li&gt;
&lt;li&gt;Repository usage from controllers.&lt;/li&gt;
&lt;li&gt;Spring proxy annotations cannot work.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;That is enough to be useful. Humans should review code like humans. Tests should reject mechanical mistakes like tests. That is the real value of executable Spring Boot best practices.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;The rules in this post come from my &lt;a href="https://protsenko.dev/spring-data-jpa-guide/" rel="noopener noreferrer"&gt;Spring Data JPA guide&lt;/a&gt;. Start with &lt;a href="https://protsenko.dev/spring-data-jpa-best-practices-entity-design-guide/" rel="noopener noreferrer"&gt;Spring Data JPA Best Practices: Entity Design Guide&lt;/a&gt;.&lt;/strong&gt;&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;&lt;strong&gt;Found this useful?&lt;/strong&gt; Follow me on social media to stay updated.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://t.me/protsenko_dev" rel="noopener noreferrer"&gt;Telegram&lt;/a&gt; · &lt;a href="https://www.linkedin.com/in/protsenkodev/" rel="noopener noreferrer"&gt;LinkedIn&lt;/a&gt;&lt;/p&gt;
&lt;/blockquote&gt;

</description>
      <category>java</category>
      <category>springboot</category>
      <category>bestpractices</category>
      <category>codequality</category>
    </item>
    <item>
      <title>Java Interview Questions for Experienced Developers: 10 Code Review Tasks</title>
      <dc:creator>Dmitry Protsenko</dc:creator>
      <pubDate>Fri, 30 Oct 2026 15:00:00 +0000</pubDate>
      <link>https://dev.to/protsenko/java-interview-questions-for-experienced-developers-10-code-review-tasks-4ojc</link>
      <guid>https://dev.to/protsenko/java-interview-questions-for-experienced-developers-10-code-review-tasks-4ojc</guid>
      <description>&lt;p&gt;These ten Java snippets look like code from a normal pull request, and each one hides a bug that breaks production.&lt;/p&gt;

&lt;p&gt;When I conducted Java interviews, code review tasks were the best way to start a real conversation. A candidate can memorize what a HashMap does. Applying it to strange code is a different skill, and it shows the level faster than 100 questions about theory.&lt;/p&gt;

&lt;p&gt;The tasks go from Java core to Spring Boot. I built every snippet on Spring Boot 4.1.1 (Hibernate 7.4.5, Jackson 3.1.5) and Java 21, and checked the main bugs with unit tests that reproduce them.&lt;/p&gt;

&lt;h2&gt;
  
  
  How to run a code review interview
&lt;/h2&gt;

&lt;p&gt;Share the code and ask one question: “What’s wrong with it?” Don’t tell the candidate how many problems there are. Watch which problem catches their eye first and how they rank them. Then ask the follow-up questions from each task.&lt;/p&gt;

&lt;div class="table-wrapper-paragraph"&gt;&lt;table&gt;
&lt;thead&gt;
&lt;tr&gt;
&lt;th&gt;#&lt;/th&gt;
&lt;th&gt;Task&lt;/th&gt;
&lt;th&gt;Topic&lt;/th&gt;
&lt;/tr&gt;
&lt;/thead&gt;
&lt;tbody&gt;
&lt;tr&gt;
&lt;td&gt;1&lt;/td&gt;
&lt;td&gt;Remove a user from a list&lt;/td&gt;
&lt;td&gt;Collections, strings&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;2&lt;/td&gt;
&lt;td&gt;Seats as HashMap keys&lt;/td&gt;
&lt;td&gt;equals and hashCode&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;3&lt;/td&gt;
&lt;td&gt;Visit counter in a Spring service&lt;/td&gt;
&lt;td&gt;Threads&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;4&lt;/td&gt;
&lt;td&gt;Report with a parallel stream&lt;/td&gt;
&lt;td&gt;Streams&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;5&lt;/td&gt;
&lt;td&gt;Login check&lt;/td&gt;
&lt;td&gt;SQL injection, passwords&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;6&lt;/td&gt;
&lt;td&gt;Token authenticator&lt;/td&gt;
&lt;td&gt;JWT, Jackson&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;7&lt;/td&gt;
&lt;td&gt;Password change&lt;/td&gt;
&lt;td&gt;Spring transactions, proxies&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;8&lt;/td&gt;
&lt;td&gt;Wallet entity and service&lt;/td&gt;
&lt;td&gt;Spring Data JPA&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;9&lt;/td&gt;
&lt;td&gt;SMS after shipping&lt;/td&gt;
&lt;td&gt;Side effects, idempotency&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;10&lt;/td&gt;
&lt;td&gt;A cleanup job with a green test&lt;/td&gt;
&lt;td&gt;Testing&lt;/td&gt;
&lt;/tr&gt;
&lt;/tbody&gt;
&lt;/table&gt;&lt;/div&gt;

&lt;h2&gt;
  
  
  Java core
&lt;/h2&gt;

&lt;h3&gt;
  
  
  Task 1. Remove a user from a list
&lt;/h3&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight java"&gt;&lt;code&gt;&lt;span class="kd"&gt;public&lt;/span&gt; &lt;span class="kd"&gt;class&lt;/span&gt; &lt;span class="nc"&gt;UserCleanup&lt;/span&gt; &lt;span class="o"&gt;{&lt;/span&gt;

    &lt;span class="kd"&gt;public&lt;/span&gt; &lt;span class="kd"&gt;static&lt;/span&gt; &lt;span class="nc"&gt;List&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="nc"&gt;String&lt;/span&gt;&lt;span class="o"&gt;&amp;gt;&lt;/span&gt; &lt;span class="nf"&gt;removeUser&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="nc"&gt;List&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="nc"&gt;String&lt;/span&gt;&lt;span class="o"&gt;&amp;gt;&lt;/span&gt; &lt;span class="n"&gt;users&lt;/span&gt;&lt;span class="o"&gt;,&lt;/span&gt; &lt;span class="nc"&gt;String&lt;/span&gt; &lt;span class="n"&gt;userToRemove&lt;/span&gt;&lt;span class="o"&gt;)&lt;/span&gt; &lt;span class="o"&gt;{&lt;/span&gt;
        &lt;span class="k"&gt;for&lt;/span&gt; &lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="nc"&gt;String&lt;/span&gt; &lt;span class="n"&gt;user&lt;/span&gt; &lt;span class="o"&gt;:&lt;/span&gt; &lt;span class="n"&gt;users&lt;/span&gt;&lt;span class="o"&gt;)&lt;/span&gt; &lt;span class="o"&gt;{&lt;/span&gt;
            &lt;span class="k"&gt;if&lt;/span&gt; &lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="n"&gt;user&lt;/span&gt; &lt;span class="o"&gt;==&lt;/span&gt; &lt;span class="n"&gt;userToRemove&lt;/span&gt;&lt;span class="o"&gt;)&lt;/span&gt; &lt;span class="o"&gt;{&lt;/span&gt;
                &lt;span class="n"&gt;users&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;remove&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="n"&gt;user&lt;/span&gt;&lt;span class="o"&gt;);&lt;/span&gt;
            &lt;span class="o"&gt;}&lt;/span&gt;
        &lt;span class="o"&gt;}&lt;/span&gt;
        &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="n"&gt;users&lt;/span&gt;&lt;span class="o"&gt;;&lt;/span&gt;
    &lt;span class="o"&gt;}&lt;/span&gt;
&lt;span class="o"&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;ol&gt;
&lt;li&gt;If the caller passes a list from List.of, remove throws UnsupportedOperationException. The method signature promises nothing about mutability.&lt;/li&gt;
&lt;li&gt;Removing inside a for-each loop throws ConcurrentModificationException on the next iteration. Remove the second-to-last element and nothing throws: the loop just stops and never checks the last element.&lt;/li&gt;
&lt;li&gt;The == operator compares references. It works in a unit test because string literals are interned, and fails for a name that came from a request or a database.&lt;/li&gt;
&lt;li&gt;The method changes the caller’s list and returns it, so the return value hides a side effect.&lt;/li&gt;
&lt;li&gt;A null list throws NullPointerException.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;A version that leaves the input alone and compares values builds a new list:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight java"&gt;&lt;code&gt;&lt;span class="kd"&gt;public&lt;/span&gt; &lt;span class="kd"&gt;class&lt;/span&gt; &lt;span class="nc"&gt;UserCleanup&lt;/span&gt; &lt;span class="o"&gt;{&lt;/span&gt;

    &lt;span class="kd"&gt;public&lt;/span&gt; &lt;span class="kd"&gt;static&lt;/span&gt; &lt;span class="nc"&gt;List&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="nc"&gt;String&lt;/span&gt;&lt;span class="o"&gt;&amp;gt;&lt;/span&gt; &lt;span class="nf"&gt;withoutUser&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="nc"&gt;List&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="nc"&gt;String&lt;/span&gt;&lt;span class="o"&gt;&amp;gt;&lt;/span&gt; &lt;span class="n"&gt;users&lt;/span&gt;&lt;span class="o"&gt;,&lt;/span&gt; &lt;span class="nc"&gt;String&lt;/span&gt; &lt;span class="n"&gt;userToRemove&lt;/span&gt;&lt;span class="o"&gt;)&lt;/span&gt; &lt;span class="o"&gt;{&lt;/span&gt;
        &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="n"&gt;users&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;stream&lt;/span&gt;&lt;span class="o"&gt;()&lt;/span&gt;
                &lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;filter&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="n"&gt;user&lt;/span&gt; &lt;span class="o"&gt;-&amp;gt;&lt;/span&gt; &lt;span class="o"&gt;!&lt;/span&gt;&lt;span class="nc"&gt;Objects&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;equals&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="n"&gt;user&lt;/span&gt;&lt;span class="o"&gt;,&lt;/span&gt; &lt;span class="n"&gt;userToRemove&lt;/span&gt;&lt;span class="o"&gt;))&lt;/span&gt;
                &lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;toList&lt;/span&gt;&lt;span class="o"&gt;();&lt;/span&gt;
    &lt;span class="o"&gt;}&lt;/span&gt;
&lt;span class="o"&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Follow-up questions:&lt;/strong&gt; What changes if the input is a LinkedList? What does removeIf do differently from removing in a loop?&lt;/p&gt;

&lt;h3&gt;
  
  
  Task 2. Seats as HashMap keys
&lt;/h3&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight java"&gt;&lt;code&gt;&lt;span class="kd"&gt;public&lt;/span&gt; &lt;span class="kd"&gt;class&lt;/span&gt; &lt;span class="nc"&gt;Seat&lt;/span&gt; &lt;span class="o"&gt;{&lt;/span&gt;

    &lt;span class="kd"&gt;private&lt;/span&gt; &lt;span class="nc"&gt;String&lt;/span&gt; &lt;span class="n"&gt;row&lt;/span&gt;&lt;span class="o"&gt;;&lt;/span&gt;
    &lt;span class="kd"&gt;private&lt;/span&gt; &lt;span class="kd"&gt;final&lt;/span&gt; &lt;span class="nc"&gt;Integer&lt;/span&gt; &lt;span class="n"&gt;number&lt;/span&gt;&lt;span class="o"&gt;;&lt;/span&gt;

    &lt;span class="kd"&gt;public&lt;/span&gt; &lt;span class="nf"&gt;Seat&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="nc"&gt;String&lt;/span&gt; &lt;span class="n"&gt;row&lt;/span&gt;&lt;span class="o"&gt;,&lt;/span&gt; &lt;span class="nc"&gt;Integer&lt;/span&gt; &lt;span class="n"&gt;number&lt;/span&gt;&lt;span class="o"&gt;)&lt;/span&gt; &lt;span class="o"&gt;{&lt;/span&gt;
        &lt;span class="k"&gt;this&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;row&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;row&lt;/span&gt;&lt;span class="o"&gt;;&lt;/span&gt;
        &lt;span class="k"&gt;this&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;number&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;number&lt;/span&gt;&lt;span class="o"&gt;;&lt;/span&gt;
    &lt;span class="o"&gt;}&lt;/span&gt;

    &lt;span class="kd"&gt;public&lt;/span&gt; &lt;span class="kt"&gt;void&lt;/span&gt; &lt;span class="nf"&gt;moveTo&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="nc"&gt;String&lt;/span&gt; &lt;span class="n"&gt;row&lt;/span&gt;&lt;span class="o"&gt;)&lt;/span&gt; &lt;span class="o"&gt;{&lt;/span&gt;
        &lt;span class="k"&gt;this&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;row&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;row&lt;/span&gt;&lt;span class="o"&gt;;&lt;/span&gt;
    &lt;span class="o"&gt;}&lt;/span&gt;

    &lt;span class="nd"&gt;@Override&lt;/span&gt;
    &lt;span class="kd"&gt;public&lt;/span&gt; &lt;span class="kt"&gt;boolean&lt;/span&gt; &lt;span class="nf"&gt;equals&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="nc"&gt;Object&lt;/span&gt; &lt;span class="n"&gt;o&lt;/span&gt;&lt;span class="o"&gt;)&lt;/span&gt; &lt;span class="o"&gt;{&lt;/span&gt;
        &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="n"&gt;o&lt;/span&gt; &lt;span class="k"&gt;instanceof&lt;/span&gt; &lt;span class="nc"&gt;Seat&lt;/span&gt; &lt;span class="n"&gt;other&lt;/span&gt; &lt;span class="o"&gt;&amp;amp;&amp;amp;&lt;/span&gt; &lt;span class="n"&gt;row&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;equals&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="n"&gt;other&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;row&lt;/span&gt;&lt;span class="o"&gt;)&lt;/span&gt; &lt;span class="o"&gt;&amp;amp;&amp;amp;&lt;/span&gt; &lt;span class="n"&gt;number&lt;/span&gt; &lt;span class="o"&gt;==&lt;/span&gt; &lt;span class="n"&gt;other&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;number&lt;/span&gt;&lt;span class="o"&gt;;&lt;/span&gt;
    &lt;span class="o"&gt;}&lt;/span&gt;
&lt;span class="o"&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;ol&gt;
&lt;li&gt;equals without hashCode. Two equal seats get different identity hash codes, so a HashMap never finds a booking by a new Seat object, and a HashSet keeps both.&lt;/li&gt;
&lt;li&gt;The number is an Integer compared with ==. Integer.valueOf caches values from -128 to 127, so seat 127 equals seat 127, and seat 128 doesn’t equal seat 128.&lt;/li&gt;
&lt;li&gt;A seat with a null row throws NullPointerException from equals.&lt;/li&gt;
&lt;li&gt;moveTo changes a field that takes part in equality. Add the missing hashCode and a moved seat gets lost inside a HashSet, because it sits in the bucket of its old hash.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;A record gives equals and hashCode over immutable components:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight java"&gt;&lt;code&gt;&lt;span class="kd"&gt;public&lt;/span&gt; &lt;span class="kd"&gt;record&lt;/span&gt; &lt;span class="nf"&gt;Seat&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="nc"&gt;String&lt;/span&gt; &lt;span class="n"&gt;row&lt;/span&gt;&lt;span class="o"&gt;,&lt;/span&gt; &lt;span class="kt"&gt;int&lt;/span&gt; &lt;span class="n"&gt;number&lt;/span&gt;&lt;span class="o"&gt;)&lt;/span&gt; &lt;span class="o"&gt;{&lt;/span&gt;
&lt;span class="o"&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Follow-up questions:&lt;/strong&gt; Why does a record need no hand-written hashCode, and when would you still write one? What breaks if a subclass adds a field and overrides equals?&lt;/p&gt;

&lt;h3&gt;
  
  
  Task 3. Visit counter in a Spring service
&lt;/h3&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight java"&gt;&lt;code&gt;&lt;span class="nd"&gt;@Service&lt;/span&gt;
&lt;span class="kd"&gt;public&lt;/span&gt; &lt;span class="kd"&gt;class&lt;/span&gt; &lt;span class="nc"&gt;VisitCounter&lt;/span&gt; &lt;span class="o"&gt;{&lt;/span&gt;

    &lt;span class="kd"&gt;private&lt;/span&gt; &lt;span class="kd"&gt;final&lt;/span&gt; &lt;span class="nc"&gt;Map&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="nc"&gt;String&lt;/span&gt;&lt;span class="o"&gt;,&lt;/span&gt; &lt;span class="nc"&gt;Integer&lt;/span&gt;&lt;span class="o"&gt;&amp;gt;&lt;/span&gt; &lt;span class="n"&gt;visits&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="k"&gt;new&lt;/span&gt; &lt;span class="nc"&gt;HashMap&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&amp;gt;();&lt;/span&gt;

    &lt;span class="kd"&gt;public&lt;/span&gt; &lt;span class="kt"&gt;void&lt;/span&gt; &lt;span class="nf"&gt;visit&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="nc"&gt;String&lt;/span&gt; &lt;span class="n"&gt;page&lt;/span&gt;&lt;span class="o"&gt;)&lt;/span&gt; &lt;span class="o"&gt;{&lt;/span&gt;
        &lt;span class="nc"&gt;Integer&lt;/span&gt; &lt;span class="n"&gt;count&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;visits&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;get&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="n"&gt;page&lt;/span&gt;&lt;span class="o"&gt;);&lt;/span&gt;
        &lt;span class="n"&gt;visits&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;put&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="n"&gt;page&lt;/span&gt;&lt;span class="o"&gt;,&lt;/span&gt; &lt;span class="n"&gt;count&lt;/span&gt; &lt;span class="o"&gt;==&lt;/span&gt; &lt;span class="kc"&gt;null&lt;/span&gt; &lt;span class="o"&gt;?&lt;/span&gt; &lt;span class="mi"&gt;1&lt;/span&gt; &lt;span class="o"&gt;:&lt;/span&gt; &lt;span class="n"&gt;count&lt;/span&gt; &lt;span class="o"&gt;+&lt;/span&gt; &lt;span class="mi"&gt;1&lt;/span&gt;&lt;span class="o"&gt;);&lt;/span&gt;
    &lt;span class="o"&gt;}&lt;/span&gt;

    &lt;span class="kd"&gt;public&lt;/span&gt; &lt;span class="kt"&gt;int&lt;/span&gt; &lt;span class="nf"&gt;visits&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="nc"&gt;String&lt;/span&gt; &lt;span class="n"&gt;page&lt;/span&gt;&lt;span class="o"&gt;)&lt;/span&gt; &lt;span class="o"&gt;{&lt;/span&gt;
        &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="n"&gt;visits&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;get&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="n"&gt;page&lt;/span&gt;&lt;span class="o"&gt;);&lt;/span&gt;
    &lt;span class="o"&gt;}&lt;/span&gt;
&lt;span class="o"&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;ol&gt;
&lt;li&gt;A Spring service is a singleton, so every request thread shares one HashMap. HashMap isn’t thread-safe, and concurrent puts can lose entries.&lt;/li&gt;
&lt;li&gt;Get, then put, is check-then-act. Two threads read 5 and both write 6. Swap in a ConcurrentHashMap and the update still gets lost: a thread-safe map doesn’t make two calls atomic.&lt;/li&gt;
&lt;li&gt;visits throws NullPointerException for a page nobody opened, because a null Integer is unboxed to int.&lt;/li&gt;
&lt;li&gt;The page comes from the request. Every new query string adds a key that nothing evicts, so the map grows until the heap runs out.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;Atomic per-key updates fix the race:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight java"&gt;&lt;code&gt;&lt;span class="nd"&gt;@Service&lt;/span&gt;
&lt;span class="kd"&gt;public&lt;/span&gt; &lt;span class="kd"&gt;class&lt;/span&gt; &lt;span class="nc"&gt;VisitCounter&lt;/span&gt; &lt;span class="o"&gt;{&lt;/span&gt;

    &lt;span class="kd"&gt;private&lt;/span&gt; &lt;span class="kd"&gt;final&lt;/span&gt; &lt;span class="nc"&gt;ConcurrentHashMap&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="nc"&gt;String&lt;/span&gt;&lt;span class="o"&gt;,&lt;/span&gt; &lt;span class="nc"&gt;LongAdder&lt;/span&gt;&lt;span class="o"&gt;&amp;gt;&lt;/span&gt; &lt;span class="n"&gt;visits&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="k"&gt;new&lt;/span&gt; &lt;span class="nc"&gt;ConcurrentHashMap&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&amp;gt;();&lt;/span&gt;

    &lt;span class="kd"&gt;public&lt;/span&gt; &lt;span class="kt"&gt;void&lt;/span&gt; &lt;span class="nf"&gt;visit&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="nc"&gt;String&lt;/span&gt; &lt;span class="n"&gt;page&lt;/span&gt;&lt;span class="o"&gt;)&lt;/span&gt; &lt;span class="o"&gt;{&lt;/span&gt;
        &lt;span class="n"&gt;visits&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;computeIfAbsent&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="n"&gt;page&lt;/span&gt;&lt;span class="o"&gt;,&lt;/span&gt; &lt;span class="n"&gt;key&lt;/span&gt; &lt;span class="o"&gt;-&amp;gt;&lt;/span&gt; &lt;span class="k"&gt;new&lt;/span&gt; &lt;span class="nc"&gt;LongAdder&lt;/span&gt;&lt;span class="o"&gt;()).&lt;/span&gt;&lt;span class="na"&gt;increment&lt;/span&gt;&lt;span class="o"&gt;();&lt;/span&gt;
    &lt;span class="o"&gt;}&lt;/span&gt;

    &lt;span class="kd"&gt;public&lt;/span&gt; &lt;span class="kt"&gt;long&lt;/span&gt; &lt;span class="nf"&gt;visits&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="nc"&gt;String&lt;/span&gt; &lt;span class="n"&gt;page&lt;/span&gt;&lt;span class="o"&gt;)&lt;/span&gt; &lt;span class="o"&gt;{&lt;/span&gt;
        &lt;span class="nc"&gt;LongAdder&lt;/span&gt; &lt;span class="n"&gt;count&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;visits&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;get&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="n"&gt;page&lt;/span&gt;&lt;span class="o"&gt;);&lt;/span&gt;
        &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="n"&gt;count&lt;/span&gt; &lt;span class="o"&gt;==&lt;/span&gt; &lt;span class="kc"&gt;null&lt;/span&gt; &lt;span class="o"&gt;?&lt;/span&gt; &lt;span class="mi"&gt;0&lt;/span&gt; &lt;span class="o"&gt;:&lt;/span&gt; &lt;span class="n"&gt;count&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;sum&lt;/span&gt;&lt;span class="o"&gt;();&lt;/span&gt;
    &lt;span class="o"&gt;}&lt;/span&gt;
&lt;span class="o"&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The fix still counts per instance: three pods keep three counters. The keys still need a limit, for example only known routes.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Follow-up questions:&lt;/strong&gt; Is a synchronized method enough? When is LongAdder better than AtomicLong?&lt;/p&gt;

&lt;h3&gt;
  
  
  Task 4. Report with a parallel stream
&lt;/h3&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight java"&gt;&lt;code&gt;&lt;span class="kd"&gt;public&lt;/span&gt; &lt;span class="kd"&gt;class&lt;/span&gt; &lt;span class="nc"&gt;ReportService&lt;/span&gt; &lt;span class="o"&gt;{&lt;/span&gt;

    &lt;span class="kd"&gt;public&lt;/span&gt; &lt;span class="nc"&gt;List&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="nc"&gt;MemberSummary&lt;/span&gt;&lt;span class="o"&gt;&amp;gt;&lt;/span&gt; &lt;span class="nf"&gt;summarize&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="nc"&gt;List&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="nc"&gt;Member&lt;/span&gt;&lt;span class="o"&gt;&amp;gt;&lt;/span&gt; &lt;span class="n"&gt;members&lt;/span&gt;&lt;span class="o"&gt;)&lt;/span&gt; &lt;span class="o"&gt;{&lt;/span&gt;
        &lt;span class="nc"&gt;List&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="nc"&gt;MemberSummary&lt;/span&gt;&lt;span class="o"&gt;&amp;gt;&lt;/span&gt; &lt;span class="n"&gt;summaries&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="k"&gt;new&lt;/span&gt; &lt;span class="nc"&gt;ArrayList&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&amp;gt;();&lt;/span&gt;
        &lt;span class="n"&gt;members&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;parallelStream&lt;/span&gt;&lt;span class="o"&gt;().&lt;/span&gt;&lt;span class="na"&gt;forEach&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="n"&gt;member&lt;/span&gt; &lt;span class="o"&gt;-&amp;gt;&lt;/span&gt; &lt;span class="o"&gt;{&lt;/span&gt;
            &lt;span class="k"&gt;if&lt;/span&gt; &lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="n"&gt;member&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;inactive&lt;/span&gt;&lt;span class="o"&gt;())&lt;/span&gt; &lt;span class="o"&gt;{&lt;/span&gt;
                &lt;span class="n"&gt;members&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;remove&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="n"&gt;member&lt;/span&gt;&lt;span class="o"&gt;);&lt;/span&gt;
            &lt;span class="o"&gt;}&lt;/span&gt; &lt;span class="k"&gt;else&lt;/span&gt; &lt;span class="o"&gt;{&lt;/span&gt;
                &lt;span class="n"&gt;summaries&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;add&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="nc"&gt;MemberSummary&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;from&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="n"&gt;member&lt;/span&gt;&lt;span class="o"&gt;));&lt;/span&gt;
            &lt;span class="o"&gt;}&lt;/span&gt;
        &lt;span class="o"&gt;});&lt;/span&gt;
        &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="n"&gt;summaries&lt;/span&gt;&lt;span class="o"&gt;;&lt;/span&gt;
    &lt;span class="o"&gt;}&lt;/span&gt;
&lt;span class="o"&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;This method can throw four exception types. While every member is active and the list is short, it usually works, so it can live in production for a long time.&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;ConcurrentModificationException. The stream iterates members, and remove changes the same list. The spliterator checks the modification count after its traversal and throws.&lt;/li&gt;
&lt;li&gt;ArrayIndexOutOfBoundsException, or summaries that silently go missing. Pool threads call add on one unsynchronized ArrayList at the same time.&lt;/li&gt;
&lt;li&gt;UnsupportedOperationException when the caller passes List.of or any unmodifiable list.&lt;/li&gt;
&lt;li&gt;NullPointerException for a null list.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;The method also changes the caller’s list, and a failure leaves it half changed. Parallel forEach doesn’t keep the order, and parallelStream adds overhead with nothing measured to justify it.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight java"&gt;&lt;code&gt;&lt;span class="kd"&gt;public&lt;/span&gt; &lt;span class="kd"&gt;class&lt;/span&gt; &lt;span class="nc"&gt;ReportService&lt;/span&gt; &lt;span class="o"&gt;{&lt;/span&gt;

    &lt;span class="kd"&gt;public&lt;/span&gt; &lt;span class="nc"&gt;List&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="nc"&gt;MemberSummary&lt;/span&gt;&lt;span class="o"&gt;&amp;gt;&lt;/span&gt; &lt;span class="nf"&gt;summarize&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="nc"&gt;List&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="nc"&gt;Member&lt;/span&gt;&lt;span class="o"&gt;&amp;gt;&lt;/span&gt; &lt;span class="n"&gt;members&lt;/span&gt;&lt;span class="o"&gt;)&lt;/span&gt; &lt;span class="o"&gt;{&lt;/span&gt;
        &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="n"&gt;members&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;stream&lt;/span&gt;&lt;span class="o"&gt;()&lt;/span&gt;
                &lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;filter&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="n"&gt;member&lt;/span&gt; &lt;span class="o"&gt;-&amp;gt;&lt;/span&gt; &lt;span class="o"&gt;!&lt;/span&gt;&lt;span class="n"&gt;member&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;inactive&lt;/span&gt;&lt;span class="o"&gt;())&lt;/span&gt;
                &lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;map&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="nl"&gt;MemberSummary:&lt;/span&gt;&lt;span class="o"&gt;:&lt;/span&gt;&lt;span class="n"&gt;from&lt;/span&gt;&lt;span class="o"&gt;)&lt;/span&gt;
                &lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;toList&lt;/span&gt;&lt;span class="o"&gt;();&lt;/span&gt;
    &lt;span class="o"&gt;}&lt;/span&gt;
&lt;span class="o"&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Follow-up questions:&lt;/strong&gt; Which thread pool runs a parallel stream? When does parallelStream help?&lt;/p&gt;

&lt;h2&gt;
  
  
  Security
&lt;/h2&gt;

&lt;h3&gt;
  
  
  Task 5. Login check with JdbcTemplate
&lt;/h3&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight java"&gt;&lt;code&gt;&lt;span class="nd"&gt;@Repository&lt;/span&gt;
&lt;span class="kd"&gt;public&lt;/span&gt; &lt;span class="kd"&gt;class&lt;/span&gt; &lt;span class="nc"&gt;LoginRepository&lt;/span&gt; &lt;span class="o"&gt;{&lt;/span&gt;

    &lt;span class="kd"&gt;private&lt;/span&gt; &lt;span class="kd"&gt;final&lt;/span&gt; &lt;span class="nc"&gt;JdbcTemplate&lt;/span&gt; &lt;span class="n"&gt;jdbc&lt;/span&gt;&lt;span class="o"&gt;;&lt;/span&gt;

    &lt;span class="kd"&gt;public&lt;/span&gt; &lt;span class="nf"&gt;LoginRepository&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="nc"&gt;JdbcTemplate&lt;/span&gt; &lt;span class="n"&gt;jdbc&lt;/span&gt;&lt;span class="o"&gt;)&lt;/span&gt; &lt;span class="o"&gt;{&lt;/span&gt;
        &lt;span class="k"&gt;this&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;jdbc&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;jdbc&lt;/span&gt;&lt;span class="o"&gt;;&lt;/span&gt;
    &lt;span class="o"&gt;}&lt;/span&gt;

    &lt;span class="kd"&gt;public&lt;/span&gt; &lt;span class="kt"&gt;boolean&lt;/span&gt; &lt;span class="nf"&gt;canLogin&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="nc"&gt;String&lt;/span&gt; &lt;span class="n"&gt;username&lt;/span&gt;&lt;span class="o"&gt;,&lt;/span&gt; &lt;span class="nc"&gt;String&lt;/span&gt; &lt;span class="n"&gt;password&lt;/span&gt;&lt;span class="o"&gt;)&lt;/span&gt; &lt;span class="o"&gt;{&lt;/span&gt;
        &lt;span class="nc"&gt;String&lt;/span&gt; &lt;span class="n"&gt;sql&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nc"&gt;String&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;format&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;
                &lt;span class="s"&gt;"SELECT COUNT(*) FROM users WHERE username = '%s' AND password = '%s'"&lt;/span&gt;&lt;span class="o"&gt;,&lt;/span&gt;
                &lt;span class="n"&gt;username&lt;/span&gt;&lt;span class="o"&gt;,&lt;/span&gt; &lt;span class="n"&gt;password&lt;/span&gt;&lt;span class="o"&gt;);&lt;/span&gt;
        &lt;span class="nc"&gt;Integer&lt;/span&gt; &lt;span class="n"&gt;count&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;jdbc&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;queryForObject&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="n"&gt;sql&lt;/span&gt;&lt;span class="o"&gt;,&lt;/span&gt; &lt;span class="nc"&gt;Integer&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;class&lt;/span&gt;&lt;span class="o"&gt;);&lt;/span&gt;
        &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="n"&gt;count&lt;/span&gt; &lt;span class="o"&gt;&amp;gt;&lt;/span&gt; &lt;span class="mi"&gt;0&lt;/span&gt;&lt;span class="o"&gt;;&lt;/span&gt;
    &lt;span class="o"&gt;}&lt;/span&gt;
&lt;span class="o"&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Only 3 out of 10 candidates found the critical issues in this task during my interviews.&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;SQL injection. String.format doesn’t escape anything. The first line as a username logs in without a password. The second line as a password logs in as anyone:
&lt;/li&gt;
&lt;/ol&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight sql"&gt;&lt;code&gt;&lt;span class="k"&gt;admin&lt;/span&gt;&lt;span class="s1"&gt;' --
'&lt;/span&gt; &lt;span class="k"&gt;OR&lt;/span&gt; &lt;span class="s1"&gt;'1'&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="s1"&gt;'1
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Passwords are stored as plain text, because the query compares the raw input with the column. One database leak, and every password is out, including the ones people reuse on other sites.&lt;/p&gt;

&lt;p&gt;No validation. A null username becomes the text “null” in the query. Blank input goes straight to the database too.&lt;/p&gt;

&lt;p&gt;COUNT(*) greater than zero hides duplicates. Nothing in this code notices two rows for one username.&lt;/p&gt;

&lt;p&gt;A common follow-up: would plain JDBC fix it? No. Statement with concatenation has the same hole. Parameters fix it, whether you use JdbcTemplate or JPA:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight java"&gt;&lt;code&gt;&lt;span class="nd"&gt;@Repository&lt;/span&gt;
&lt;span class="kd"&gt;public&lt;/span&gt; &lt;span class="kd"&gt;class&lt;/span&gt; &lt;span class="nc"&gt;LoginRepository&lt;/span&gt; &lt;span class="o"&gt;{&lt;/span&gt;

    &lt;span class="kd"&gt;private&lt;/span&gt; &lt;span class="kd"&gt;final&lt;/span&gt; &lt;span class="nc"&gt;JdbcTemplate&lt;/span&gt; &lt;span class="n"&gt;jdbc&lt;/span&gt;&lt;span class="o"&gt;;&lt;/span&gt;
    &lt;span class="kd"&gt;private&lt;/span&gt; &lt;span class="kd"&gt;final&lt;/span&gt; &lt;span class="nc"&gt;PasswordEncoder&lt;/span&gt; &lt;span class="n"&gt;passwordEncoder&lt;/span&gt;&lt;span class="o"&gt;;&lt;/span&gt;

    &lt;span class="kd"&gt;public&lt;/span&gt; &lt;span class="nf"&gt;LoginRepository&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="nc"&gt;JdbcTemplate&lt;/span&gt; &lt;span class="n"&gt;jdbc&lt;/span&gt;&lt;span class="o"&gt;,&lt;/span&gt; &lt;span class="nc"&gt;PasswordEncoder&lt;/span&gt; &lt;span class="n"&gt;passwordEncoder&lt;/span&gt;&lt;span class="o"&gt;)&lt;/span&gt; &lt;span class="o"&gt;{&lt;/span&gt;
        &lt;span class="k"&gt;this&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;jdbc&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;jdbc&lt;/span&gt;&lt;span class="o"&gt;;&lt;/span&gt;
        &lt;span class="k"&gt;this&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;passwordEncoder&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;passwordEncoder&lt;/span&gt;&lt;span class="o"&gt;;&lt;/span&gt;
    &lt;span class="o"&gt;}&lt;/span&gt;

    &lt;span class="kd"&gt;public&lt;/span&gt; &lt;span class="kt"&gt;boolean&lt;/span&gt; &lt;span class="nf"&gt;canLogin&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="nc"&gt;String&lt;/span&gt; &lt;span class="n"&gt;username&lt;/span&gt;&lt;span class="o"&gt;,&lt;/span&gt; &lt;span class="nc"&gt;String&lt;/span&gt; &lt;span class="n"&gt;password&lt;/span&gt;&lt;span class="o"&gt;)&lt;/span&gt; &lt;span class="o"&gt;{&lt;/span&gt;
        &lt;span class="nc"&gt;List&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="nc"&gt;String&lt;/span&gt;&lt;span class="o"&gt;&amp;gt;&lt;/span&gt; &lt;span class="n"&gt;hashes&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;jdbc&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;queryForList&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;
                &lt;span class="s"&gt;"SELECT password_hash FROM users WHERE username = ?"&lt;/span&gt;&lt;span class="o"&gt;,&lt;/span&gt; &lt;span class="nc"&gt;String&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;class&lt;/span&gt;&lt;span class="o"&gt;,&lt;/span&gt; &lt;span class="n"&gt;username&lt;/span&gt;&lt;span class="o"&gt;);&lt;/span&gt;
        &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="n"&gt;hashes&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;size&lt;/span&gt;&lt;span class="o"&gt;()&lt;/span&gt; &lt;span class="o"&gt;==&lt;/span&gt; &lt;span class="mi"&gt;1&lt;/span&gt; &lt;span class="o"&gt;&amp;amp;&amp;amp;&lt;/span&gt; &lt;span class="n"&gt;passwordEncoder&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;matches&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="n"&gt;password&lt;/span&gt;&lt;span class="o"&gt;,&lt;/span&gt; &lt;span class="n"&gt;hashes&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;get&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;0&lt;/span&gt;&lt;span class="o"&gt;));&lt;/span&gt;
    &lt;span class="o"&gt;}&lt;/span&gt;
&lt;span class="o"&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The column now holds a BCrypt hash, and the encoder compares the input with it in Java. Declare a BCryptPasswordEncoder bean, because Spring Boot doesn’t create one.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Follow-up questions:&lt;/strong&gt; Why should password hashing be slow? Where else can user input reach SQL (ORDER BY, LIKE patterns)?&lt;/p&gt;

&lt;h3&gt;
  
  
  Task 6. Token authenticator
&lt;/h3&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight java"&gt;&lt;code&gt;&lt;span class="nd"&gt;@Slf4j&lt;/span&gt;
&lt;span class="nd"&gt;@Service&lt;/span&gt;
&lt;span class="kd"&gt;public&lt;/span&gt; &lt;span class="kd"&gt;class&lt;/span&gt; &lt;span class="nc"&gt;TokenAuthenticator&lt;/span&gt; &lt;span class="o"&gt;{&lt;/span&gt;

    &lt;span class="kd"&gt;private&lt;/span&gt; &lt;span class="kd"&gt;final&lt;/span&gt; &lt;span class="nc"&gt;ApiClientRepository&lt;/span&gt; &lt;span class="n"&gt;clients&lt;/span&gt;&lt;span class="o"&gt;;&lt;/span&gt;

    &lt;span class="kd"&gt;public&lt;/span&gt; &lt;span class="nf"&gt;TokenAuthenticator&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="nc"&gt;ApiClientRepository&lt;/span&gt; &lt;span class="n"&gt;clients&lt;/span&gt;&lt;span class="o"&gt;)&lt;/span&gt; &lt;span class="o"&gt;{&lt;/span&gt;
        &lt;span class="k"&gt;this&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;clients&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;clients&lt;/span&gt;&lt;span class="o"&gt;;&lt;/span&gt;
    &lt;span class="o"&gt;}&lt;/span&gt;

    &lt;span class="kd"&gt;public&lt;/span&gt; &lt;span class="nc"&gt;Optional&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="nc"&gt;ApiClient&lt;/span&gt;&lt;span class="o"&gt;&amp;gt;&lt;/span&gt; &lt;span class="nf"&gt;authenticate&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="nc"&gt;String&lt;/span&gt; &lt;span class="n"&gt;token&lt;/span&gt;&lt;span class="o"&gt;)&lt;/span&gt; &lt;span class="o"&gt;{&lt;/span&gt;
        &lt;span class="n"&gt;log&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;info&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="s"&gt;"Authenticating token {}"&lt;/span&gt;&lt;span class="o"&gt;,&lt;/span&gt; &lt;span class="n"&gt;token&lt;/span&gt;&lt;span class="o"&gt;);&lt;/span&gt;
        &lt;span class="nc"&gt;String&lt;/span&gt;&lt;span class="o"&gt;[]&lt;/span&gt; &lt;span class="n"&gt;parts&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;token&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;split&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="s"&gt;"\\."&lt;/span&gt;&lt;span class="o"&gt;);&lt;/span&gt;
        &lt;span class="nc"&gt;ObjectMapper&lt;/span&gt; &lt;span class="n"&gt;mapper&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="k"&gt;new&lt;/span&gt; &lt;span class="nc"&gt;ObjectMapper&lt;/span&gt;&lt;span class="o"&gt;();&lt;/span&gt;
        &lt;span class="nc"&gt;Map&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="nc"&gt;String&lt;/span&gt;&lt;span class="o"&gt;,&lt;/span&gt; &lt;span class="nc"&gt;Object&lt;/span&gt;&lt;span class="o"&gt;&amp;gt;&lt;/span&gt; &lt;span class="n"&gt;header&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;mapper&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;readValue&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="n"&gt;decode&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="n"&gt;parts&lt;/span&gt;&lt;span class="o"&gt;[&lt;/span&gt;&lt;span class="mi"&gt;0&lt;/span&gt;&lt;span class="o"&gt;]),&lt;/span&gt; &lt;span class="nc"&gt;Map&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;class&lt;/span&gt;&lt;span class="o"&gt;);&lt;/span&gt;
        &lt;span class="nc"&gt;Map&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="nc"&gt;String&lt;/span&gt;&lt;span class="o"&gt;,&lt;/span&gt; &lt;span class="nc"&gt;Object&lt;/span&gt;&lt;span class="o"&gt;&amp;gt;&lt;/span&gt; &lt;span class="n"&gt;claims&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;mapper&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;readValue&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="n"&gt;decode&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="n"&gt;parts&lt;/span&gt;&lt;span class="o"&gt;[&lt;/span&gt;&lt;span class="mi"&gt;1&lt;/span&gt;&lt;span class="o"&gt;]),&lt;/span&gt; &lt;span class="nc"&gt;Map&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;class&lt;/span&gt;&lt;span class="o"&gt;);&lt;/span&gt;
        &lt;span class="n"&gt;log&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;debug&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="s"&gt;"Token signed with {}"&lt;/span&gt;&lt;span class="o"&gt;,&lt;/span&gt; &lt;span class="n"&gt;header&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;get&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="s"&gt;"alg"&lt;/span&gt;&lt;span class="o"&gt;));&lt;/span&gt;
        &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="n"&gt;clients&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;findByLogin&lt;/span&gt;&lt;span class="o"&gt;((&lt;/span&gt;&lt;span class="nc"&gt;String&lt;/span&gt;&lt;span class="o"&gt;)&lt;/span&gt; &lt;span class="n"&gt;claims&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;get&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="s"&gt;"sub"&lt;/span&gt;&lt;span class="o"&gt;));&lt;/span&gt;
    &lt;span class="o"&gt;}&lt;/span&gt;

    &lt;span class="kd"&gt;private&lt;/span&gt; &lt;span class="kd"&gt;static&lt;/span&gt; &lt;span class="kt"&gt;byte&lt;/span&gt;&lt;span class="o"&gt;[]&lt;/span&gt; &lt;span class="nf"&gt;decode&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="nc"&gt;String&lt;/span&gt; &lt;span class="n"&gt;part&lt;/span&gt;&lt;span class="o"&gt;)&lt;/span&gt; &lt;span class="o"&gt;{&lt;/span&gt;
        &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="nc"&gt;Base64&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;getDecoder&lt;/span&gt;&lt;span class="o"&gt;().&lt;/span&gt;&lt;span class="na"&gt;decode&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="n"&gt;part&lt;/span&gt;&lt;span class="o"&gt;);&lt;/span&gt;
    &lt;span class="o"&gt;}&lt;/span&gt;
&lt;span class="o"&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;ol&gt;
&lt;li&gt;The signature is never checked. A token with a random signature passes, and so does a token with the header alg set to none. Anyone can write any subject.&lt;/li&gt;
&lt;li&gt;No expiration check. A token stolen a year ago still works.&lt;/li&gt;
&lt;li&gt;The full token goes to the INFO log, so anyone who reads logs can reuse it.&lt;/li&gt;
&lt;li&gt;A new ObjectMapper on every call. The mapper is expensive to build and thread-safe to share. During a load test I once saw a flame graph where 70% of CPU time was spent creating object mappers.&lt;/li&gt;
&lt;li&gt;Map plus casts. A numeric subject throws ClassCastException at runtime.&lt;/li&gt;
&lt;li&gt;JWT parts are base64url. The basic decoder rejects the – and _ characters, so some valid tokens fail with IllegalArgumentException.&lt;/li&gt;
&lt;li&gt;A string without dots throws ArrayIndexOutOfBoundsException, an unhandled exception instead of a clean 401.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;Don’t parse tokens by hand. Spring Security’s resource server checks the signature and the expiration. It checks the issuer too once you set it below. The Boot 4 starter replaces the deprecated spring-boot-starter-oauth2-resource-server, and start.spring.io adds it when you pick OAuth2 Resource Server:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;&amp;lt;!-- pom.xml --&amp;gt;
&amp;lt;dependency&amp;gt;
    &amp;lt;groupId&amp;gt;org.springframework.boot&amp;lt;/groupId&amp;gt;
    &amp;lt;artifactId&amp;gt;spring-boot-starter-security-oauth2-resource-server&amp;lt;/artifactId&amp;gt;
&amp;lt;/dependency&amp;gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;





&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight kotlin"&gt;&lt;code&gt;&lt;span class="c1"&gt;// build.gradle.kts&lt;/span&gt;
&lt;span class="nf"&gt;implementation&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s"&gt;"org.springframework.boot:spring-boot-starter-security-oauth2-resource-server"&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;





&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight ini"&gt;&lt;code&gt;&lt;span class="c"&gt;# application.properties
&lt;/span&gt;&lt;span class="py"&gt;spring.security.oauth2.resourceserver.jwt.issuer-uri&lt;/span&gt;&lt;span class="p"&gt;=&lt;/span&gt;&lt;span class="s"&gt;https://auth.example.com&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;When code needs JSON, inject the JsonMapper that Spring Boot 4 configures for Jackson 3 instead of building a new one.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Follow-up questions:&lt;/strong&gt; What does the alg header change? Why is a symmetric key risky when many services verify tokens?&lt;/p&gt;

&lt;h2&gt;
  
  
  Spring and Spring Data JPA
&lt;/h2&gt;

&lt;h3&gt;
  
  
  Task 7. Password change
&lt;/h3&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight java"&gt;&lt;code&gt;&lt;span class="nd"&gt;@Service&lt;/span&gt;
&lt;span class="kd"&gt;public&lt;/span&gt; &lt;span class="kd"&gt;class&lt;/span&gt; &lt;span class="nc"&gt;PasswordService&lt;/span&gt; &lt;span class="o"&gt;{&lt;/span&gt;

    &lt;span class="nd"&gt;@Autowired&lt;/span&gt;
    &lt;span class="kd"&gt;private&lt;/span&gt; &lt;span class="nc"&gt;AppUserRepository&lt;/span&gt; &lt;span class="n"&gt;users&lt;/span&gt;&lt;span class="o"&gt;;&lt;/span&gt;
    &lt;span class="nd"&gt;@Autowired&lt;/span&gt;
    &lt;span class="kd"&gt;private&lt;/span&gt; &lt;span class="nc"&gt;AuditLogRepository&lt;/span&gt; &lt;span class="n"&gt;auditLogs&lt;/span&gt;&lt;span class="o"&gt;;&lt;/span&gt;

    &lt;span class="kd"&gt;public&lt;/span&gt; &lt;span class="kt"&gt;void&lt;/span&gt; &lt;span class="nf"&gt;updatePassword&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="nc"&gt;Long&lt;/span&gt; &lt;span class="n"&gt;userId&lt;/span&gt;&lt;span class="o"&gt;,&lt;/span&gt; &lt;span class="nc"&gt;String&lt;/span&gt; &lt;span class="n"&gt;oldPassword&lt;/span&gt;&lt;span class="o"&gt;,&lt;/span&gt; &lt;span class="nc"&gt;String&lt;/span&gt; &lt;span class="n"&gt;newPassword&lt;/span&gt;&lt;span class="o"&gt;)&lt;/span&gt; &lt;span class="o"&gt;{&lt;/span&gt;
        &lt;span class="nc"&gt;AppUser&lt;/span&gt; &lt;span class="n"&gt;user&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;users&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;findById&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="n"&gt;userId&lt;/span&gt;&lt;span class="o"&gt;).&lt;/span&gt;&lt;span class="na"&gt;get&lt;/span&gt;&lt;span class="o"&gt;();&lt;/span&gt;
        &lt;span class="n"&gt;saveAuditLog&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="n"&gt;userId&lt;/span&gt;&lt;span class="o"&gt;,&lt;/span&gt; &lt;span class="s"&gt;"PASSWORD_CHANGE"&lt;/span&gt;&lt;span class="o"&gt;);&lt;/span&gt;
        &lt;span class="n"&gt;user&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;setPassword&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="n"&gt;newPassword&lt;/span&gt;&lt;span class="o"&gt;);&lt;/span&gt;
        &lt;span class="n"&gt;users&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;save&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="n"&gt;user&lt;/span&gt;&lt;span class="o"&gt;);&lt;/span&gt;
    &lt;span class="o"&gt;}&lt;/span&gt;

    &lt;span class="nd"&gt;@Transactional&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="n"&gt;propagation&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nc"&gt;Propagation&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;REQUIRES_NEW&lt;/span&gt;&lt;span class="o"&gt;)&lt;/span&gt;
    &lt;span class="kd"&gt;public&lt;/span&gt; &lt;span class="kt"&gt;void&lt;/span&gt; &lt;span class="nf"&gt;saveAuditLog&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="nc"&gt;Long&lt;/span&gt; &lt;span class="n"&gt;userId&lt;/span&gt;&lt;span class="o"&gt;,&lt;/span&gt; &lt;span class="nc"&gt;String&lt;/span&gt; &lt;span class="n"&gt;action&lt;/span&gt;&lt;span class="o"&gt;)&lt;/span&gt; &lt;span class="o"&gt;{&lt;/span&gt;
        &lt;span class="n"&gt;auditLogs&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;save&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="k"&gt;new&lt;/span&gt; &lt;span class="nc"&gt;AuditLog&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="n"&gt;userId&lt;/span&gt;&lt;span class="o"&gt;,&lt;/span&gt; &lt;span class="n"&gt;action&lt;/span&gt;&lt;span class="o"&gt;,&lt;/span&gt; &lt;span class="nc"&gt;LocalDateTime&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;now&lt;/span&gt;&lt;span class="o"&gt;()));&lt;/span&gt;
    &lt;span class="o"&gt;}&lt;/span&gt;
&lt;span class="o"&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;This task got the most reactions of all my interview posts on LinkedIn. The problems, from critical to minor:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;Anyone can change anyone’s password. oldPassword is never checked, and the user id comes from the caller instead of the security context.&lt;/li&gt;
&lt;li&gt;The new password is stored as plain text and never validated. A blank password passes.&lt;/li&gt;
&lt;li&gt;The audit row is saved first and committed on its own. When the update fails (for example, a null password hits a NOT NULL column), the audit log says the password changed.&lt;/li&gt;
&lt;li&gt;REQUIRES_NEW does nothing here. updatePassword calls saveAuditLog on this, not through the Spring proxy, so no new transaction starts. Called from another bean, the same method does get its own transaction.&lt;/li&gt;
&lt;li&gt;updatePassword has no transaction. The read and the write run in two separate repository transactions.&lt;/li&gt;
&lt;li&gt;Field injection hides dependencies from the constructor and makes the class harder to test.&lt;/li&gt;
&lt;li&gt;findById(…).get() throws NoSuchElementException with the message “No value present”, without the id.&lt;/li&gt;
&lt;li&gt;The action is a free string, and LocalDateTime.now() takes the server’s time zone.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;A fixed version takes the user from the security context and checks the old password with PasswordEncoder before it stores a hash of the new one. The change and its audit row commit together in one transactional method. The bean gets its repositories through the constructor.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Follow-up questions:&lt;/strong&gt; Which annotations work through the same proxy? Why can’t a private method be transactional?&lt;/p&gt;

&lt;h3&gt;
  
  
  Task 8. Wallet entity and service
&lt;/h3&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight java"&gt;&lt;code&gt;&lt;span class="nd"&gt;@Data&lt;/span&gt;
&lt;span class="nd"&gt;@Entity&lt;/span&gt;
&lt;span class="kd"&gt;public&lt;/span&gt; &lt;span class="kd"&gt;class&lt;/span&gt; &lt;span class="nc"&gt;Wallet&lt;/span&gt; &lt;span class="o"&gt;{&lt;/span&gt;

    &lt;span class="nd"&gt;@Id&lt;/span&gt;
    &lt;span class="nd"&gt;@GeneratedValue&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="n"&gt;strategy&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nc"&gt;GenerationType&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;IDENTITY&lt;/span&gt;&lt;span class="o"&gt;)&lt;/span&gt;
    &lt;span class="kd"&gt;private&lt;/span&gt; &lt;span class="nc"&gt;Long&lt;/span&gt; &lt;span class="n"&gt;id&lt;/span&gt;&lt;span class="o"&gt;;&lt;/span&gt;
    &lt;span class="kd"&gt;private&lt;/span&gt; &lt;span class="nc"&gt;String&lt;/span&gt; &lt;span class="n"&gt;owner&lt;/span&gt;&lt;span class="o"&gt;;&lt;/span&gt;
    &lt;span class="kd"&gt;private&lt;/span&gt; &lt;span class="kt"&gt;double&lt;/span&gt; &lt;span class="n"&gt;balance&lt;/span&gt;&lt;span class="o"&gt;;&lt;/span&gt;
    &lt;span class="nd"&gt;@Enumerated&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="nc"&gt;EnumType&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;ORDINAL&lt;/span&gt;&lt;span class="o"&gt;)&lt;/span&gt;
    &lt;span class="kd"&gt;private&lt;/span&gt; &lt;span class="nc"&gt;WalletStatus&lt;/span&gt; &lt;span class="n"&gt;status&lt;/span&gt;&lt;span class="o"&gt;;&lt;/span&gt;
    &lt;span class="kd"&gt;private&lt;/span&gt; &lt;span class="nc"&gt;String&lt;/span&gt; &lt;span class="n"&gt;createdAt&lt;/span&gt;&lt;span class="o"&gt;;&lt;/span&gt;
&lt;span class="o"&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;





&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight java"&gt;&lt;code&gt;&lt;span class="kd"&gt;public&lt;/span&gt; &lt;span class="kd"&gt;interface&lt;/span&gt; &lt;span class="nc"&gt;WalletRepository&lt;/span&gt; &lt;span class="kd"&gt;extends&lt;/span&gt; &lt;span class="nc"&gt;JpaRepository&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="nc"&gt;Wallet&lt;/span&gt;&lt;span class="o"&gt;,&lt;/span&gt; &lt;span class="nc"&gt;Long&lt;/span&gt;&lt;span class="o"&gt;&amp;gt;&lt;/span&gt; &lt;span class="o"&gt;{&lt;/span&gt;

    &lt;span class="nd"&gt;@Modifying&lt;/span&gt;
    &lt;span class="nd"&gt;@Query&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="s"&gt;"update Wallet w set w.status = :status"&lt;/span&gt;&lt;span class="o"&gt;)&lt;/span&gt;
    &lt;span class="kt"&gt;int&lt;/span&gt; &lt;span class="nf"&gt;setStatusForAll&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="nc"&gt;WalletStatus&lt;/span&gt; &lt;span class="n"&gt;status&lt;/span&gt;&lt;span class="o"&gt;);&lt;/span&gt;
&lt;span class="o"&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;





&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight java"&gt;&lt;code&gt;&lt;span class="nd"&gt;@Slf4j&lt;/span&gt;
&lt;span class="nd"&gt;@Service&lt;/span&gt;
&lt;span class="kd"&gt;public&lt;/span&gt; &lt;span class="kd"&gt;class&lt;/span&gt; &lt;span class="nc"&gt;WalletService&lt;/span&gt; &lt;span class="o"&gt;{&lt;/span&gt;

    &lt;span class="kd"&gt;private&lt;/span&gt; &lt;span class="kd"&gt;final&lt;/span&gt; &lt;span class="nc"&gt;WalletRepository&lt;/span&gt; &lt;span class="n"&gt;wallets&lt;/span&gt;&lt;span class="o"&gt;;&lt;/span&gt;

    &lt;span class="kd"&gt;public&lt;/span&gt; &lt;span class="nf"&gt;WalletService&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="nc"&gt;WalletRepository&lt;/span&gt; &lt;span class="n"&gt;wallets&lt;/span&gt;&lt;span class="o"&gt;)&lt;/span&gt; &lt;span class="o"&gt;{&lt;/span&gt;
        &lt;span class="k"&gt;this&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;wallets&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;wallets&lt;/span&gt;&lt;span class="o"&gt;;&lt;/span&gt;
    &lt;span class="o"&gt;}&lt;/span&gt;

    &lt;span class="kd"&gt;public&lt;/span&gt; &lt;span class="kt"&gt;void&lt;/span&gt; &lt;span class="nf"&gt;rename&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="nc"&gt;Long&lt;/span&gt; &lt;span class="n"&gt;id&lt;/span&gt;&lt;span class="o"&gt;,&lt;/span&gt; &lt;span class="nc"&gt;String&lt;/span&gt; &lt;span class="n"&gt;owner&lt;/span&gt;&lt;span class="o"&gt;)&lt;/span&gt; &lt;span class="o"&gt;{&lt;/span&gt;
        &lt;span class="nc"&gt;Wallet&lt;/span&gt; &lt;span class="n"&gt;wallet&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;wallets&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;findById&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="n"&gt;id&lt;/span&gt;&lt;span class="o"&gt;).&lt;/span&gt;&lt;span class="na"&gt;get&lt;/span&gt;&lt;span class="o"&gt;();&lt;/span&gt;
        &lt;span class="n"&gt;wallet&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;setOwner&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="n"&gt;owner&lt;/span&gt;&lt;span class="o"&gt;);&lt;/span&gt;
    &lt;span class="o"&gt;}&lt;/span&gt;

    &lt;span class="nd"&gt;@Transactional&lt;/span&gt;
    &lt;span class="kd"&gt;public&lt;/span&gt; &lt;span class="nc"&gt;List&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="nc"&gt;Wallet&lt;/span&gt;&lt;span class="o"&gt;&amp;gt;&lt;/span&gt; &lt;span class="nf"&gt;freezeAll&lt;/span&gt;&lt;span class="o"&gt;()&lt;/span&gt; &lt;span class="o"&gt;{&lt;/span&gt;
        &lt;span class="n"&gt;wallets&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;findAll&lt;/span&gt;&lt;span class="o"&gt;().&lt;/span&gt;&lt;span class="na"&gt;forEach&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="n"&gt;w&lt;/span&gt; &lt;span class="o"&gt;-&amp;gt;&lt;/span&gt; &lt;span class="n"&gt;log&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;info&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="s"&gt;"Freezing wallet of {}"&lt;/span&gt;&lt;span class="o"&gt;,&lt;/span&gt; &lt;span class="n"&gt;w&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;getOwner&lt;/span&gt;&lt;span class="o"&gt;()));&lt;/span&gt;
        &lt;span class="n"&gt;wallets&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;setStatusForAll&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="nc"&gt;WalletStatus&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;FROZEN&lt;/span&gt;&lt;span class="o"&gt;);&lt;/span&gt;
        &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="n"&gt;wallets&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;findAll&lt;/span&gt;&lt;span class="o"&gt;();&lt;/span&gt;
    &lt;span class="o"&gt;}&lt;/span&gt;
&lt;span class="o"&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;ol&gt;
&lt;li&gt;rename does nothing. Outside a web request, findById runs in its own short transaction and returns a detached entity, so setOwner changes only an object in memory.&lt;/li&gt;
&lt;li&gt;freezeAll returns stale data. The bulk update goes straight to the database and skips the persistence context. The second findAll returns the same managed wallets, still ACTIVE, while the table says FROZEN.&lt;/li&gt;
&lt;li&gt;Lombok &lt;a class="mentioned-user" href="https://dev.to/data"&gt;@data&lt;/a&gt; builds hashCode over every field, including the id. save sets the id on the same object, and a wallet put in a HashSet before saving can’t be found after.&lt;/li&gt;
&lt;li&gt;ORDINAL stores the position of the constant: FROZEN is 1. Add a constant in the middle of the enum and old rows change meaning.&lt;/li&gt;
&lt;li&gt;A double balance drifts: three deposits of 0.1 don’t add up to 0.3.&lt;/li&gt;
&lt;li&gt;IDENTITY ids turn off JDBC insert batching in Hibernate, because Hibernate has to run each insert at once to learn its id. More on batching in my &lt;a href="https://protsenko.dev/spring-data-jpa-batch-insert-performance-tuning/" rel="noopener noreferrer"&gt;Spring Data JPA batch insert article&lt;/a&gt;.&lt;/li&gt;
&lt;li&gt;createdAt is a String: no time zone, and text sorting breaks on the first different format.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;Fixes for the entity: getters and setters instead of &lt;a class="mentioned-user" href="https://dev.to/data"&gt;@data&lt;/a&gt;, EnumType.STRING, BigDecimal, Instant, and a sequence. rename needs @Transactional; dirty checking then saves the change without a save call. The bulk update needs a transaction and a cleared persistence context:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight java"&gt;&lt;code&gt;&lt;span class="kd"&gt;public&lt;/span&gt; &lt;span class="kd"&gt;interface&lt;/span&gt; &lt;span class="nc"&gt;WalletRepository&lt;/span&gt; &lt;span class="kd"&gt;extends&lt;/span&gt; &lt;span class="nc"&gt;JpaRepository&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="nc"&gt;Wallet&lt;/span&gt;&lt;span class="o"&gt;,&lt;/span&gt; &lt;span class="nc"&gt;Long&lt;/span&gt;&lt;span class="o"&gt;&amp;gt;&lt;/span&gt; &lt;span class="o"&gt;{&lt;/span&gt;

    &lt;span class="nd"&gt;@Transactional&lt;/span&gt; &lt;span class="c1"&gt;// a write needs a transaction, whoever calls it&lt;/span&gt;
    &lt;span class="nd"&gt;@Modifying&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="n"&gt;flushAutomatically&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="kc"&gt;true&lt;/span&gt;&lt;span class="o"&gt;,&lt;/span&gt; &lt;span class="n"&gt;clearAutomatically&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="kc"&gt;true&lt;/span&gt;&lt;span class="o"&gt;)&lt;/span&gt; &lt;span class="c1"&gt;// fresh reads after the update&lt;/span&gt;
    &lt;span class="nd"&gt;@Query&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="s"&gt;"update Wallet w set w.status = :status"&lt;/span&gt;&lt;span class="o"&gt;)&lt;/span&gt;
    &lt;span class="kt"&gt;int&lt;/span&gt; &lt;span class="nf"&gt;setStatusForAll&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="nc"&gt;WalletStatus&lt;/span&gt; &lt;span class="n"&gt;status&lt;/span&gt;&lt;span class="o"&gt;);&lt;/span&gt;
&lt;span class="o"&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Follow-up questions:&lt;/strong&gt; What does dirty checking need to work? What does open-in-view hide in a case like rename?&lt;/p&gt;

&lt;h3&gt;
  
  
  Task 9. SMS after shipping
&lt;/h3&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight java"&gt;&lt;code&gt;&lt;span class="nd"&gt;@Service&lt;/span&gt;
&lt;span class="kd"&gt;public&lt;/span&gt; &lt;span class="kd"&gt;class&lt;/span&gt; &lt;span class="nc"&gt;ShippingNotifier&lt;/span&gt; &lt;span class="o"&gt;{&lt;/span&gt;

    &lt;span class="kd"&gt;private&lt;/span&gt; &lt;span class="kd"&gt;final&lt;/span&gt; &lt;span class="nc"&gt;SmsGateway&lt;/span&gt; &lt;span class="n"&gt;sms&lt;/span&gt;&lt;span class="o"&gt;;&lt;/span&gt;
    &lt;span class="kd"&gt;private&lt;/span&gt; &lt;span class="kd"&gt;final&lt;/span&gt; &lt;span class="nc"&gt;NotificationRepository&lt;/span&gt; &lt;span class="n"&gt;notifications&lt;/span&gt;&lt;span class="o"&gt;;&lt;/span&gt;

    &lt;span class="kd"&gt;public&lt;/span&gt; &lt;span class="nf"&gt;ShippingNotifier&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="nc"&gt;SmsGateway&lt;/span&gt; &lt;span class="n"&gt;sms&lt;/span&gt;&lt;span class="o"&gt;,&lt;/span&gt; &lt;span class="nc"&gt;NotificationRepository&lt;/span&gt; &lt;span class="n"&gt;notifications&lt;/span&gt;&lt;span class="o"&gt;)&lt;/span&gt; &lt;span class="o"&gt;{&lt;/span&gt;
        &lt;span class="k"&gt;this&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;sms&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;sms&lt;/span&gt;&lt;span class="o"&gt;;&lt;/span&gt;
        &lt;span class="k"&gt;this&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;notifications&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;notifications&lt;/span&gt;&lt;span class="o"&gt;;&lt;/span&gt;
    &lt;span class="o"&gt;}&lt;/span&gt;

    &lt;span class="nd"&gt;@Transactional&lt;/span&gt;
    &lt;span class="kd"&gt;public&lt;/span&gt; &lt;span class="kt"&gt;void&lt;/span&gt; &lt;span class="nf"&gt;onOrderShipped&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="nc"&gt;OrderShipped&lt;/span&gt; &lt;span class="n"&gt;event&lt;/span&gt;&lt;span class="o"&gt;)&lt;/span&gt; &lt;span class="o"&gt;{&lt;/span&gt;
        &lt;span class="nc"&gt;String&lt;/span&gt; &lt;span class="n"&gt;messageId&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;sms&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;send&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="n"&gt;event&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;phone&lt;/span&gt;&lt;span class="o"&gt;(),&lt;/span&gt; &lt;span class="s"&gt;"Your order is on the way"&lt;/span&gt;&lt;span class="o"&gt;);&lt;/span&gt;
        &lt;span class="n"&gt;notifications&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;save&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="k"&gt;new&lt;/span&gt; &lt;span class="nc"&gt;Notification&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="n"&gt;event&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;orderId&lt;/span&gt;&lt;span class="o"&gt;(),&lt;/span&gt; &lt;span class="n"&gt;messageId&lt;/span&gt;&lt;span class="o"&gt;));&lt;/span&gt;
    &lt;span class="o"&gt;}&lt;/span&gt;
&lt;span class="o"&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;A real case cost a company $2,000 in duplicate SMS messages: a Kafka consumer sent the SMS and then did one more write. This snippet has the same shape.&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;@Transactional doesn’t make the flow atomic. The SMS goes out first, then the insert fails, the transaction rolls back, and the customer already has the message.&lt;/li&gt;
&lt;li&gt;No idempotency. Kafka delivers at least once, so the same event can arrive again after a timeout or a rebalance. The second delivery sends a second SMS and then fails on the unique order id, and a retrying consumer can repeat that.&lt;/li&gt;
&lt;li&gt;The transaction holds a pooled database connection during the HTTP call to the SMS provider. A slow provider can drain the pool for the whole service.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;A safer shape: save a pending notification with the order id as the idempotency key. Send the SMS after the commit, from an outbox table or an AFTER_COMMIT listener. Mark it sent, and only then acknowledge the Kafka offset.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Follow-up questions:&lt;/strong&gt; What happens if the service crashes after the SMS but before it marks the notification sent? Where does the consumer acknowledge the message?&lt;/p&gt;

&lt;h3&gt;
  
  
  Task 10. A cleanup job with a green test
&lt;/h3&gt;

&lt;p&gt;This one is close to a bug I shipped myself: the test for a scheduled @Modifying query was green, and in production the job silently did nothing.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight java"&gt;&lt;code&gt;&lt;span class="nd"&gt;@Component&lt;/span&gt;
&lt;span class="kd"&gt;public&lt;/span&gt; &lt;span class="kd"&gt;class&lt;/span&gt; &lt;span class="nc"&gt;SessionCleanup&lt;/span&gt; &lt;span class="o"&gt;{&lt;/span&gt;

    &lt;span class="kd"&gt;private&lt;/span&gt; &lt;span class="kd"&gt;final&lt;/span&gt; &lt;span class="nc"&gt;LoginSessionRepository&lt;/span&gt; &lt;span class="n"&gt;sessions&lt;/span&gt;&lt;span class="o"&gt;;&lt;/span&gt;

    &lt;span class="kd"&gt;public&lt;/span&gt; &lt;span class="nf"&gt;SessionCleanup&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="nc"&gt;LoginSessionRepository&lt;/span&gt; &lt;span class="n"&gt;sessions&lt;/span&gt;&lt;span class="o"&gt;)&lt;/span&gt; &lt;span class="o"&gt;{&lt;/span&gt;
        &lt;span class="k"&gt;this&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;sessions&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;sessions&lt;/span&gt;&lt;span class="o"&gt;;&lt;/span&gt;
    &lt;span class="o"&gt;}&lt;/span&gt;

    &lt;span class="nd"&gt;@Scheduled&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="n"&gt;cron&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="s"&gt;"0 0 * * * *"&lt;/span&gt;&lt;span class="o"&gt;)&lt;/span&gt;
    &lt;span class="kd"&gt;public&lt;/span&gt; &lt;span class="kt"&gt;void&lt;/span&gt; &lt;span class="nf"&gt;removeExpired&lt;/span&gt;&lt;span class="o"&gt;()&lt;/span&gt; &lt;span class="o"&gt;{&lt;/span&gt;
        &lt;span class="n"&gt;sessions&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;deleteExpired&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="nc"&gt;Instant&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;now&lt;/span&gt;&lt;span class="o"&gt;());&lt;/span&gt;
    &lt;span class="o"&gt;}&lt;/span&gt;
&lt;span class="o"&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;





&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight java"&gt;&lt;code&gt;&lt;span class="kd"&gt;public&lt;/span&gt; &lt;span class="kd"&gt;interface&lt;/span&gt; &lt;span class="nc"&gt;LoginSessionRepository&lt;/span&gt; &lt;span class="kd"&gt;extends&lt;/span&gt; &lt;span class="nc"&gt;JpaRepository&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="nc"&gt;LoginSession&lt;/span&gt;&lt;span class="o"&gt;,&lt;/span&gt; &lt;span class="nc"&gt;Long&lt;/span&gt;&lt;span class="o"&gt;&amp;gt;&lt;/span&gt; &lt;span class="o"&gt;{&lt;/span&gt;

    &lt;span class="nd"&gt;@Modifying&lt;/span&gt;
    &lt;span class="nd"&gt;@Query&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="s"&gt;"delete from LoginSession s where s.expiresAt &amp;lt; :now"&lt;/span&gt;&lt;span class="o"&gt;)&lt;/span&gt;
    &lt;span class="kt"&gt;int&lt;/span&gt; &lt;span class="nf"&gt;deleteExpired&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="nc"&gt;Instant&lt;/span&gt; &lt;span class="n"&gt;now&lt;/span&gt;&lt;span class="o"&gt;);&lt;/span&gt;
&lt;span class="o"&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;





&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight java"&gt;&lt;code&gt;&lt;span class="nd"&gt;@DataJpaTest&lt;/span&gt;
&lt;span class="nd"&gt;@Import&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="nc"&gt;SessionCleanup&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;class&lt;/span&gt;&lt;span class="o"&gt;)&lt;/span&gt;
&lt;span class="kd"&gt;class&lt;/span&gt; &lt;span class="nc"&gt;SessionCleanupTest&lt;/span&gt; &lt;span class="o"&gt;{&lt;/span&gt;

    &lt;span class="nd"&gt;@Autowired&lt;/span&gt;
    &lt;span class="nc"&gt;SessionCleanup&lt;/span&gt; &lt;span class="n"&gt;cleanup&lt;/span&gt;&lt;span class="o"&gt;;&lt;/span&gt;
    &lt;span class="nd"&gt;@Autowired&lt;/span&gt;
    &lt;span class="nc"&gt;LoginSessionRepository&lt;/span&gt; &lt;span class="n"&gt;sessions&lt;/span&gt;&lt;span class="o"&gt;;&lt;/span&gt;

    &lt;span class="nd"&gt;@Test&lt;/span&gt;
    &lt;span class="kt"&gt;void&lt;/span&gt; &lt;span class="nf"&gt;removesExpiredSessions&lt;/span&gt;&lt;span class="o"&gt;()&lt;/span&gt; &lt;span class="o"&gt;{&lt;/span&gt;
        &lt;span class="n"&gt;sessions&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;save&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="k"&gt;new&lt;/span&gt; &lt;span class="nc"&gt;LoginSession&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="nc"&gt;Instant&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;now&lt;/span&gt;&lt;span class="o"&gt;().&lt;/span&gt;&lt;span class="na"&gt;minusSeconds&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;60&lt;/span&gt;&lt;span class="o"&gt;)));&lt;/span&gt;
        &lt;span class="n"&gt;cleanup&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;removeExpired&lt;/span&gt;&lt;span class="o"&gt;();&lt;/span&gt;
        &lt;span class="n"&gt;assertThat&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="n"&gt;sessions&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;count&lt;/span&gt;&lt;span class="o"&gt;()).&lt;/span&gt;&lt;span class="na"&gt;isZero&lt;/span&gt;&lt;span class="o"&gt;();&lt;/span&gt;
    &lt;span class="o"&gt;}&lt;/span&gt;
&lt;span class="o"&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The test is green. In production the job throws InvalidDataAccessApiUsageException caused by TransactionRequiredException on every run, and the scheduler only logs it.&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;Spring Data JPA applies no transaction to your own query methods. A @Modifying query needs one, and the scheduler calls removeExpired without it.&lt;/li&gt;
&lt;li&gt;@DataJpaTest wraps each test in a transaction. The test borrows that transaction, and production has none.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;The fix puts the transaction on the write:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight java"&gt;&lt;code&gt;&lt;span class="kd"&gt;public&lt;/span&gt; &lt;span class="kd"&gt;interface&lt;/span&gt; &lt;span class="nc"&gt;LoginSessionRepository&lt;/span&gt; &lt;span class="kd"&gt;extends&lt;/span&gt; &lt;span class="nc"&gt;JpaRepository&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="nc"&gt;LoginSession&lt;/span&gt;&lt;span class="o"&gt;,&lt;/span&gt; &lt;span class="nc"&gt;Long&lt;/span&gt;&lt;span class="o"&gt;&amp;gt;&lt;/span&gt; &lt;span class="o"&gt;{&lt;/span&gt;

    &lt;span class="nd"&gt;@Transactional&lt;/span&gt; &lt;span class="c1"&gt;// the scheduler calls it without a transaction&lt;/span&gt;
    &lt;span class="nd"&gt;@Modifying&lt;/span&gt;
    &lt;span class="nd"&gt;@Query&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="s"&gt;"delete from LoginSession s where s.expiresAt &amp;lt; :now"&lt;/span&gt;&lt;span class="o"&gt;)&lt;/span&gt;
    &lt;span class="kt"&gt;int&lt;/span&gt; &lt;span class="nf"&gt;deleteExpired&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="nc"&gt;Instant&lt;/span&gt; &lt;span class="n"&gt;now&lt;/span&gt;&lt;span class="o"&gt;);&lt;/span&gt;
&lt;span class="o"&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The bigger fix is in the tests. Run integration tests with @SpringBootTest and without @Transactional on test classes. An ArchUnit rule can fail the build when someone adds @DataJpaTest or @Transactional to an integration test again.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Follow-up questions:&lt;/strong&gt; Which repository methods are transactional by default? How else can a test transaction hide a bug?&lt;/p&gt;

&lt;h2&gt;
  
  
  Spring Boot good practices to ask about
&lt;/h2&gt;

&lt;p&gt;Tasks 5, 7, 8 and 9 break at least one of these, and a candidate can explain them without any code.&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;Constructor injection. Required dependencies are final, and a unit test can build the class without Spring.&lt;/li&gt;
&lt;li&gt;HTTP stays in the controller layer. Services throw domain exceptions such as UserNotFoundException, and a @RestControllerAdvice maps them to responses.&lt;/li&gt;
&lt;li&gt;Turn on Problem Details for errors. It is off by default:
&lt;/li&gt;
&lt;/ol&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight ini"&gt;&lt;code&gt;&lt;span class="c"&gt;# application.properties
&lt;/span&gt;&lt;span class="py"&gt;spring.mvc.problemdetails.enabled&lt;/span&gt;&lt;span class="p"&gt;=&lt;/span&gt;&lt;span class="s"&gt;true&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Return DTOs, not entities. An entity leaks internal fields such as a password hash, and lazy associations fail after the transaction closes.&lt;/p&gt;

&lt;p&gt;Turn off open-in-view. Spring Boot 4.1 still turns it on by default and only logs a warning. It keeps the database session open while the response renders and hides lazy loading problems:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight ini"&gt;&lt;code&gt;&lt;span class="c"&gt;# application.properties
&lt;/span&gt;&lt;span class="py"&gt;spring.jpa.open-in-view&lt;/span&gt;&lt;span class="p"&gt;=&lt;/span&gt;&lt;span class="s"&gt;false&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;





&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight ini"&gt;&lt;code&gt;&lt;span class="c"&gt;# application.properties
&lt;/span&gt;&lt;span class="py"&gt;spring.jpa.hibernate.ddl-auto&lt;/span&gt;&lt;span class="p"&gt;=&lt;/span&gt;&lt;span class="s"&gt;validate&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Validate input at the edge with Bean Validation on request DTOs, then trust the types inside.&lt;/p&gt;

&lt;p&gt;Tokens and secrets never go in the URL. Query parameters end up in access logs and proxy logs.&lt;/p&gt;

&lt;p&gt;Every write that a client or a broker can retry needs an idempotency key.&lt;/p&gt;

&lt;p&gt;Which of these tasks would you give a candidate first, and which bug did you miss on the first read?&lt;/p&gt;

&lt;h2&gt;
  
  
  At the end
&lt;/h2&gt;

&lt;p&gt;If you like this post, follow me on &lt;a href="https://www.linkedin.com/in/protsenkodev/" rel="noopener noreferrer"&gt;LinkedIn&lt;/a&gt; for new code review tasks. More on entities and transactions: &lt;a href="https://protsenko.dev/spring-data-jpa-guide/" rel="noopener noreferrer"&gt;Spring Data JPA guide&lt;/a&gt;.&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;&lt;strong&gt;Found this useful?&lt;/strong&gt; Follow me on social media to stay updated.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://t.me/protsenko_dev" rel="noopener noreferrer"&gt;Telegram&lt;/a&gt; · &lt;a href="https://www.linkedin.com/in/protsenkodev/" rel="noopener noreferrer"&gt;LinkedIn&lt;/a&gt;&lt;/p&gt;
&lt;/blockquote&gt;

</description>
      <category>java</category>
      <category>interview</category>
      <category>codereview</category>
      <category>programming</category>
    </item>
  </channel>
</rss>
