<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Mohamed Bouguern on Medium]]></title>
        <description><![CDATA[Stories by Mohamed Bouguern on Medium]]></description>
        <link>https://medium.com/@bouguern.mohamed?source=rss-9126d0af0ba2------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*1Xu-V3iDzsebmQPwWFQEcQ.jpeg</url>
            <title>Stories by Mohamed Bouguern on Medium</title>
            <link>https://medium.com/@bouguern.mohamed?source=rss-9126d0af0ba2------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 23 Nov 2026 21:15:37 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@bouguern.mohamed/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[I Built a CV Screening Tool for Recruiters in Java — Here’s How, and Why the AI Never Decides]]></title>
            <link>https://medium.com/@bouguern.mohamed/i-built-a-cv-screening-tool-for-recruiters-in-java-heres-how-and-why-the-ai-never-decides-70158f15b485?source=rss-9126d0af0ba2------2</link>
            <guid isPermaLink="false">https://medium.com/p/70158f15b485</guid>
            <category><![CDATA[cv-writing]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[generative-ai-tools]]></category>
            <category><![CDATA[langchain4j]]></category>
            <category><![CDATA[spring-boot]]></category>
            <dc:creator><![CDATA[Mohamed Bouguern]]></dc:creator>
            <pubDate>Wed, 24 Jun 2026 15:00:02 GMT</pubDate>
            <atom:updated>2026-06-24T15:03:40.831Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_0j6tUvpOO-DIAyx31mn3g.jpeg" /></figure><p>After hearing many recruiters and companies say the same thing — that it’s hard to read every CV carefully for a position and give each candidate a fair justification — I did some research, and I think I found something that can help.</p><p><strong>The stack:</strong> Spring Boot 3, Java 21, LangChain4j with a local Ollama model, Apache Tika for reading real files, and PostgreSQL for an audit trail. It takes a real PDF, extracts the candidate’s profile, scores them against a job description, and returns a recommendation a recruiter can actually act on.</p><h3>Why this isn’t just a ChatGPT prompt</h3><p>The obvious objection first, because I had it too. You can paste a CV and a job posting into ChatGPT and ask “is this a fit?” It works, sort of. So why build anything?</p><p>Because real screening isn’t a single question. It’s a small process with branches:</p><p>- A scanned or badly formatted PDF needs to be re-read, not silently mangled.<br>- A strong match and an ambiguous one shouldn’t be treated the same way.<br>- And — this is the one most people skip — “the AI said no” is not an acceptable answer when a candidate, a manager, or a regulator asks why someone was rejected.</p><p>A one-shot prompt gives you a black box. What a recruiter actually needs is a pipeline: extract, check confidence, retry if needed, escalate to a human when uncertain, score on fixed rules, and always produce a written reason. That’s the difference between a clever demo and something you’d let near a real hiring funnel.</p><h3>The shape of the thing</h3><p>The flow is deliberately boring, in the good way:</p><p>A recruiter uploads a CV file and pastes the job description. Apache Tika pulls the text out — it auto-detects PDF, DOCX, or plain text, so the recruiter doesn’t have to think about formats. The text goes to the screening service, which does the real work, and the result lands in PostgreSQL with a full audit trail before the JSON comes back.</p><p>The service itself reads like the process I described above:</p><pre>public ScreeningResult screen(String rawCv, JobSpec job) {<br>    List&lt;String&gt; audit = new ArrayList&lt;&gt;();<br><br>    // 1. extract candidate profile + job requirements<br>    var extraction = llm.extractProfile(rawCv, job, 1);<br><br>    // 2. retry once if the extraction was weak<br>    if (!extraction.profile().isReliable(properties.minExtractionConfidence())) {<br>        extraction = llm.extractProfile(rawCv, job, 2);<br>    }<br><br>    // 3. still unreliable? hand it to a human instead of guessing<br>    if (!extraction.profile().isReliable(properties.minExtractionConfidence())) {<br>        return escalateToHuman(rawCv, job, extraction, audit);<br>    }<br><br>    // 4. score on fixed rules — no LLM here<br>    int score = rubric.score(extraction.profile(),<br>            extraction.requiredSkills(), extraction.minRequiredYears());<br><br>    // 5. turn the score into a recommendation<br>    var recommendation = rubric.recommend(score);<br><br>    // 6. write an evidence-based justification (reads the full CV)<br>    String justification = llm.explain(rawCv, extraction.profile(), job,<br>            extraction.requiredSkills(), extraction.minRequiredYears(),<br>            score, recommendation);<br><br>    return new ScreeningResult(/* ... */);<br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4EaKLDbNyctGE7y1kEySIw.jpeg" /></figure><p>No framework magic. You can read it top to bottom and know exactly what happens. I’ll come back to why I deliberately kept it this simple.</p><h3>The decision I’m proudest of: the AI doesn’t score</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9_LWsodRl-ZpXTBmaIj19g.jpeg" /></figure><p>It would have been easy to ask the model “rate this candidate 0 to 100.” I didn’t, and I’d push back on anyone who does.</p><p>Scoring has to be reproducible. The same CV against the same job has to produce the same number today, next week, and when a manager asks me to explain it six months from now. An LLM can’t promise that — ask it twice and you might get 72 and then 78. So the scoring is plain Java:</p><pre>public int score(CandidateProfile profile, List&lt;String&gt; requiredSkills, int minYears) {<br>    double skillScore = requiredSkills.isEmpty() ? 0.0<br>            : (double) requiredSkills.stream()<br>                    .filter(profile.skills()::contains).count()<br>              / requiredSkills.size() * properties.skillWeight();<br><br>    double experienceScore = minYears &lt;= 0<br>            ? properties.experienceWeight()<br>            : Math.min(1.0, (double) profile.yearsExperience() / minYears)<br>              * properties.experienceWeight();<br><br>    return (int) Math.round(skillScore + experienceScore);<br>}</pre><p>The LLM is reserved for the two things it’s genuinely good at and that plain code can’t do: turning a messy, bilingual CV into structured data, and writing a justification a human can read. Everything that should be a rule stays a rule. That line — model for ambiguity, code for accountability — is the whole design philosophy in one sentence.</p><p>The same thinking applies to confidence. I don’t ask the model “how sure are you?” — a model that confidently hallucinates will confidently tell you it’s confident. Instead I compute confidence from how many fields actually came back populated. It’s a small thing that removes a whole category of nonsense.</p><h3>Making the explanation actually mean something</h3><p>Here’s a subtlety I got wrong in my first version. If you only score on a skills list and a years count, you throw away the most valuable part of a CV — the substance. The bullet that says “led migration of five microservices to Kubernetes, cut response time 40%” collapses into the tag “kubernetes.” Two candidates who both list Kafka score identically, even if one architected an event-driven platform and the other sat in a workshop.</p><p>I didn’t fix this with embeddings or a vector database — for this, that’s overkill. I fixed it with the explanation step. The justification call receives the <strong>full CV text</strong>, not just the extracted fields, and it’s instructed to cite concrete evidence from the experience bullets:</p><p>Strong backend evidence — led a production microservices migration with a measurable 40% latency improvement. Direct Kubernetes experience isn’t stated, though related container work appears in the Havas project. Recommendation: shortlist, pending a check on orchestration depth.</p><p>The critical constraint: the justification <strong>explains</strong> the recommendation the rules already made — it can never override the score. If the rubric says NOT_RECOMMENDED, the prose can’t suddenly call the candidate a perfect fit. The model reads deeply and writes richly, but the number stays deterministic. That’s the whole trick: the LLM makes the <strong>explanation</strong> smarter without touching the <strong>decision</strong>. It’s strictly an improvement to explainability, which, as you’ll see, is exactly what the law wants more of.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lGIEeYa4xky0MxIu99TXxQ.jpeg" /></figure><h3>Two ports, and not one more</h3><p>I work mostly on the French market — clients like Havas and, through Capgemini, AXA — and the one architectural lesson that keeps proving itself is: isolate the parts that change, and don’t ceremony-ize the parts that don’t.</p><p>There are exactly two things in this system that are genuinely volatile: which LLM I talk to, and how I read a file. So those are the only two interfaces — `LlmScreeningPort` and `CvTextExtractor`. Everything else is plain layered packages. This isn’t full hexagonal architecture with a port for everything; that would bury the actual logic under abstraction. It’s hexagonal where it pays off and simple everywhere else.</p><p>The payoff is concrete. Today this runs on a local Ollama model — free, no API key, you can clone the repo and run it tonight. Want to move it to Groq or OpenAI for production scale? One adapter class changes. The service, the scoring, the controller, the database — none of it knows or cares which model answers. That’s what the boundary buys you.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6vn2A1w3Xkg2p5mq511ErQ.jpeg" /></figure><h3>The part that makes it legal-friendly</h3><p>CV-screening AI is classified as high-risk under the EU AI Act. That doesn’t mean banned — it means allowed under conditions: human oversight, explainability, and audit logging. I built around that from the start, and you can see it in the code, not just the README.</p><p>Look at the naming. The output type isn’t called `Decision` and there’s no `REJECT`:</p><pre>public enum ScreeningRecommendation {<br>    SHORTLIST,<br>    NOT_RECOMMENDED,<br>    NEEDS_HUMAN_REVIEW<br>}</pre><p>It’s a <strong>recommendation</strong>. The class that handles an unreadable CV doesn’t guess — it routes to a person. Every screening, whatever the outcome, ends with a written justification and a full audit trail saved to PostgreSQL. A candidate has the right to an explanation; this gives them one, grounded in the actual content of their CV.</p><p>I want to be precise here, because precision is the point: this is a reference implementation of the pattern, not a certified-compliant product. Real compliance needs a bias audit, candidate transparency notices, and a named human overseer with actual authority — things a repository can’t provide on its own. What the architecture guarantees is narrower and real: the AI is structurally incapable of making the final call. A recruiter always does.</p><h3>What I left out, on purpose</h3><p>Naming the gaps honestly is part of showing what this is — and what it isn’t yet. Three are worth calling out specifically, because they’re the most interesting.</p><ul><li><strong>It screens one CV at a time.</strong> This keeps the article focused on the pipeline, but it’s not how a recruiter works — they have a stack of fifty CVs for one opening and want them ranked, best match first. Adding that is straightforward: the screening logic doesn’t change, you loop over the files and sort by score. What deserves real thought is running it at volume. Sequentially, fifty CVs through a local model takes a few minutes — fine for a demo, not for production. The production path is asynchronous: the recruiter uploads the batch, gets a job ID back immediately, and the work happens in the background, ready to poll or pushed when done. True parallelism only helps once the LLM runs on a backend that handles concurrent requests — a single local Ollama instance processes one inference at a time no matter how many you throw at it. So batch ranking is the obvious next feature; doing it asynchronously is what makes it production-grade. I left both out on purpose — the goal was a clear pattern, not a scaling exercise.</li><li><strong>The models carry American assumptions.</strong> This one fascinates me. The LLMs behind tools like this — Llama, GPT, Claude — are American-trained, and they quietly assume an “American CV”: one page, no photo, no personal details, achievement-first bullets. But a German CV correctly includes a photo and a complete chronological history; a French CV weighs the <strong>grande école</strong> heavily; a Spanish one often follows the Europass format. To an American-trained model, those perfectly correct European CVs can look <strong>wrong</strong>. This build treats every CV neutrally — it doesn’t yet know these cultural differences. Making the scoring genuinely aware of French, Spanish, and German hiring norms is the natural next step, and honestly the part I find most worth building, because almost no existing tool gets it right.</li><li><strong>And the usual production checklist:</strong> authentication on the API, database migrations instead of Hibernate auto-DDL, rate limiting, virus scanning on uploads, and — the non-negotiable one — independent bias testing before this goes near real candidates. None of these are hard individually. But a half-finished security feature looks worse than a clearly labeled roadmap, so I’d rather list them than fake them.</li></ul><h3>Try it</h3><p>The whole thing runs locally. Pull the model, start the services, upload a CV:</p><pre>ollama pull llama3.2<br>docker-compose up -d</pre><p>Then open Swagger at `<a href="http://localhost:9090/swagger-ui.html%60">http://localhost:9090/swagger-ui.html`</a> and screen a CV right from the browser — no curl required.</p><p>The code is on <a href="https://github.com/bouguern/AI-powered-CV-screening-workflow-for-HR">GitHub</a>. Clone it, run it against your own CV and a job you’re eyeing, and see what it says. I found the result genuinely useful for spotting what my own CV was failing to communicate — which, honestly, was the moment I knew the thing was worth finishing.</p><p>If it saves one recruiter one Friday evening, it was worth building.</p><p>I write about Java, Spring Boot, Angular, and bringing AI into real production systems. If that’s your world too, follow along.</p><p>Thank you.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=70158f15b485" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building an AI complaint classifier with Spring AI, engineering the prompt from 60% to 100%…]]></title>
            <link>https://medium.com/@bouguern.mohamed/building-an-ai-complaint-classifier-with-spring-ai-engineering-the-prompt-from-60-to-100-78ef812e1178?source=rss-9126d0af0ba2------2</link>
            <guid isPermaLink="false">https://medium.com/p/78ef812e1178</guid>
            <category><![CDATA[spring-boot]]></category>
            <category><![CDATA[prompt-engineering]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[spring-ai]]></category>
            <category><![CDATA[writing-prompts]]></category>
            <dc:creator><![CDATA[Mohamed Bouguern]]></dc:creator>
            <pubDate>Thu, 28 May 2026 11:06:23 GMT</pubDate>
            <atom:updated>2026-05-28T11:06:23.093Z</atom:updated>
            <content:encoded><![CDATA[<h3>Building an AI complaint classifier with Spring AI, engineering the prompt from 60% to 100% accuracy, and the eval harness that grades every change</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-j86DVZOuNcEoUD0mzMKSg.png" /></figure><p>Most articles about AI features show you one thing: how to wire up an LLM call. This one shows the whole picture, because in real work the LLM call is the easy part. What actually matters is three pillars:</p><ol><li><strong>Building</strong> the feature — a real AI complaint classifier in Spring Boot.</li><li><strong>Engineering</strong> the prompt — taking it from mediocre to reliable through measured iteration.</li><li><strong>Evaluating</strong> it — an eval harness that proves, with a number, that the feature works.</li></ol><p>Skip any one of these and you don’t have a production AI feature. You have a demo.</p><h4>The problem nobody talks about</h4><p>In a normal Spring Boot feature, testing is simple. You call a method, you get a result, you check it matches:</p><pre>input:    &quot;2 + 2&quot;<br>expected: &quot;4&quot;</pre><p>Either it passes or it doesn’t. assertEquals(&quot;4&quot;, result). Done.</p><p>Then you add an AI feature. You wire up an LLM, ship it, and write… one test. Maybe two. You run it once by hand, it looks fine, and you move on.</p><p>Here’s the uncomfortable truth: <strong>most AI features in production have no real tests at all.</strong> Not because developers are lazy — because the testing tools they know simply don’t work anymore.</p><h4>Why assertEquals breaks</h4><p>An LLM is non-deterministic. The same input gives you a different answer every time:</p><ul><li>“The answer is 4”</li><li>“That equals 4”</li><li>“2 + 2 = 4, of course!”</li></ul><p>All three are correct. <strong>None of them pass </strong><strong>assertEquals(&quot;4&quot;).</strong></p><p>So the moment you put an LLM behind a feature, your entire testing reflex stops working. And most teams’ response is to just… stop testing. They ship the feature, watch it in production, and hope.</p><p>Then one day someone tweaks a prompt — changes one sentence — and quietly breaks 30% of the outputs. Nobody notices for three weeks.</p><h4>The shift: test properties, not exact output</h4><p>The fix is a change in mindset.</p><p>Instead of checking the <em>exact output</em>, you check the <em>properties of the output</em>.</p><p>Think of training a new employee to answer customer emails. You don’t tell them “your reply must be exactly these 40 words.” You tell them: <em>Was it polite? Did it mention the order number? Did it avoid promising a refund we can’t give?</em></p><p>That’s an <strong>eval set</strong> — a collection of real example inputs, each paired with a checklist of what a good answer looks like. And the code that runs all those checks automatically is an <strong>eval harness</strong>.</p><p>It’s a test suite, adapted for the fact that LLM output is never the same twice.</p><h4>The three checks</h4><p>A good eval harness runs three layers of checks:</p><p><strong>1. Structural check</strong> — Is the output usable at all? Are all fields present? Are the values valid? No LLM needed — pure code.</p><p><strong>2. Semantic check</strong> — Is the answer correct? Compare it against your golden dataset (the human-written answer key). This is the accuracy score.</p><p><strong>3. Regression check</strong> — You changed the prompt. Did the score go up or down? This is what catches the “quietly broke 30% of outputs” disaster <em>before</em> it ships.</p><p>There’s also an optional fourth technique — <strong>LLM-as-judge</strong> — which we’ll come back to.</p><h3>Pillar 1 — Building the classifier</h3><p>To make this concrete, we’ll build a real feature: an <strong>AI customer complaint classifier</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4J4WmFFG67LEfTVK08uCuA.png" /></figure><p>A customer sends a complaint. The service classifies it by:</p><ul><li><strong>Category</strong> — BILLING, TECHNICAL, DELIVERY, ACCOUNT, or OTHER</li><li><strong>Urgency</strong> — LOW, MEDIUM, HIGH, or CRITICAL</li><li><strong>Routing team</strong> — which team should handle it</li></ul><p>Stack: <strong>Java 21, Spring Boot 3.4, Spring AI 1.0, PostgreSQL.</strong> Every bank, insurer, and telecom has this exact problem — and misrouting a complaint in a regulated sector has real consequences.</p><p>The core is small. Spring AI maps the LLM response straight into a Java record:</p><pre>public record ClassificationResult(<br>        @JsonPropertyDescription(&quot;Category: BILLING, TECHNICAL, DELIVERY, ACCOUNT, or OTHER&quot;)<br>        ComplaintCategory category,<br><br>        @JsonPropertyDescription(&quot;Urgency: LOW, MEDIUM, HIGH, or CRITICAL&quot;)<br>        UrgencyLevel urgency,<br><br>        @JsonPropertyDescription(&quot;Exact team name to route to&quot;)<br>        String suggestedTeam,<br><br>        @JsonPropertyDescription(&quot;One sentence explaining the decision&quot;)<br>        String reasoning<br>) {}</pre><p>Those @JsonPropertyDescription annotations aren&#39;t comments — Spring AI embeds them into the JSON schema sent to the model, which measurably improves accuracy.</p><p>The classifier itself:</p><pre>public ClassificationResult classify(String complaintText) {<br>    String rendered = promptTemplate.replace(&quot;{complaint}&quot;, complaintText);<br><br>    return chatClient.prompt()<br>            .user(rendered)<br>            .call()<br>            .entity(ClassificationResult.class);<br>}</pre><p>A prompt, a call, a typed result. Every complaint and every classification is persisted to PostgreSQL — an audit trail, which in a regulated sector is not optional.</p><p>The interesting question isn’t <em>“does this run?”</em> — it’s <em>“is it right?”</em></p><h3>Pillar 3 — The eval harness (we’ll come back to Pillar 2)</h3><h4>The golden dataset</h4><p>This is the answer key. A JSON file of real complaints where <strong>you, the human</strong>, decided the correct answer in advance:</p><pre>[<br>  {<br>    &quot;id&quot;: &quot;case-02&quot;,<br>    &quot;complaintText&quot;: &quot;Someone made three purchases on my account totaling $1,200 that I did not authorize.&quot;,<br>    &quot;expectedCategory&quot;: &quot;BILLING&quot;,<br>    &quot;expectedUrgency&quot;: &quot;CRITICAL&quot;,<br>    &quot;expectedTeam&quot;: &quot;Billing Support Team&quot;<br>  },<br>  {<br>    &quot;id&quot;: &quot;case-07&quot;,<br>    &quot;complaintText&quot;: &quot;Pages are loading a bit slowly today. Not a big deal but thought I would mention it.&quot;,<br>    &quot;expectedCategory&quot;: &quot;TECHNICAL&quot;,<br>    &quot;expectedUrgency&quot;: &quot;LOW&quot;,<br>    &quot;expectedTeam&quot;: &quot;Technical Support Team&quot;<br>  }<br>]</pre><p>Twenty cases, covering every category, every urgency level, and several deliberately tricky edge cases. The AI never sees this file — it’s used only for grading.</p><h4>The checks</h4><p><strong>Structural check</strong> — pure Java validation:</p><pre>if (!VALID_TEAMS.contains(result.suggestedTeam())) {<br>    failures.add(&quot;suggestedTeam not in the allowed list&quot;);<br>}</pre><p><strong>Semantic check</strong> — direct comparison against the golden dataset:</p><pre>boolean categoryMatch = actual.category() == expected.expectedCategory();<br>boolean urgencyMatch  = actual.urgency()  == expected.expectedUrgency();<br>boolean teamMatch     = actual.suggestedTeam().equals(expected.expectedTeam());<br><br>boolean passed = categoryMatch &amp;&amp; urgencyMatch &amp;&amp; teamMatch;</pre><p><strong>Regression scorer</strong> — compares two runs and tells you, plainly, whether to ship:</p><pre>double delta = candidate.getScore() - baseline.getScore();<br>String summary = delta &gt; 0<br>        ? &quot;Improved by +&quot; + delta + &quot;% — safe to deploy&quot;<br>        : &quot;Regressed by &quot; + delta + &quot;% — DO NOT deploy&quot;;</pre><p>Every run is saved to an eval_runs table, tagged with the prompt version that produced it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lS-Nv_E1Or9uHYZRfTAuqA.png" /></figure><h4>Running against a real API: rate limits and cost</h4><p>The moment you run an eval against a real LLM provider, you hit two practical walls the tutorials never mention. Both are worth understanding, because how you handle them is what separates production thinking from a demo.</p><h4>Rate limits — why we add a delay</h4><p>Free and entry tiers of LLM APIs cap how many tokens you can send <strong>per minute</strong>. Our eval fires 20 classification calls in quick succession — and on a free tier, that blows straight past the limit. The API starts returning HTTP 429 — rate limit exceeded, and cases fail not because the AI was wrong, but because we asked too fast.</p><p>The fix is simple and deliberate — a pause between calls:</p><pre>result = classifier.classify(evalCase.complaintText());<br>Thread.sleep(4000); // stay under the provider&#39;s per-minute token limit</pre><p>Why four seconds? Each call uses roughly 700–800 tokens. Twenty calls is around 15,000 tokens. If the provider’s limit is 12,000 tokens per minute, you must spread those calls across more than a minute — so four seconds per call (about 80 seconds total) keeps every request safely inside the window.</p><p>It feels crude, and it is. But it matters: with the delay, <strong>every failure in the report is a real failure worth fixing</strong>, not noise from a rate limit. In production on a paid tier you would remove this or replace it with proper exponential backoff. For an eval run on a free tier, a fixed pause is the honest, pragmatic choice — and naming <em>why</em> it’s there is part of writing the harness properly.</p><h4>Cost — why the LLM-as-judge is off by default</h4><p>Remember the optional fourth technique, LLM-as-judge? Here’s how it works: for every case that <em>fails</em> the semantic check, you make a <strong>second LLM call</strong> asking another model “is this classification reasonable, even though it differs from the expected answer?” It catches cases where the AI’s answer is defensibly correct and your golden dataset is simply too strict.</p><p>It’s genuinely useful. But it isn’t free. Every judge call costs extra tokens and counts against the same rate limit. Running it on every eval, on a free tier, will trigger 429s and slow everything down.</p><p>So we make it a switch:</p><pre>private static final boolean RUN_LLM_JUDGE = false;</pre><p>Off by default: the eval runs fast and cheap, using only the 20 classification calls it actually needs. Flip it to true when you specifically want the deeper analysis and have the API budget for it. The judge code is fully implemented and ready — you simply choose <em>when</em> to spend tokens on it.</p><p>This is the lesson hiding inside a small boolean: an eval harness is not free to run. Knowing when it costs you, and giving yourself a deliberate switch, is part of building it like an engineer instead of a hobbyist.</p><h3>Pillar 2 — Engineering the prompt: from 60% to 100%</h3><p>Now the heart of the article. We ran the eval harness three times, improving the prompt between each run. Watch the numbers.</p><h4>Version 1 — the first honest attempt</h4><p>The first prompt was reasonable. Clear categories, clear urgency definitions. We ran the eval:</p><pre>RESULTS - prompt v1<br>Structural:  20/20<br>Semantic:    12/20<br>Score:       60.0%</pre><p><strong>60%.</strong> One in three complaints misclassified. Without the eval harness, we would have shipped this and never known. With it, we got an exact list of what was wrong:</p><ul><li>Duplicate charges classified as MEDIUM urgency instead of HIGH</li><li>A password reset failure routed to the Account team instead of Technical</li><li>“Slow page loading” classified as OTHER instead of TECHNICAL</li></ul><p>The harness didn’t just give us a score. It gave us a to-do list.</p><h4>Version 2 — fixing what the harness found</h4><p>We rewrote the prompt to address each failure. Added explicit rules: <em>“If a technical failure blocks a financial action, urgency is HIGH.”</em> Added examples for minor performance issues. Tightened the category definitions.</p><pre>RESULTS - prompt v2<br>Structural:  20/20<br>Semantic:    16/20<br>Score:       80.0%</pre><p><strong>80%.</strong> A 20-point jump from one prompt revision. The regression check confirmed it automatically:</p><pre>v1: 60.0%  →  v2: 80.0%  (delta: +20.0%)<br>→ Improved by +20.0% — safe to deploy</pre><h4>Version 3 — closing the gap</h4><p>The last failures were subtle. A duplicate charge the model didn’t see as a “financial loss.” A refund unresolved for three weeks rated MEDIUM. A feature that broke after an update rated LOW.</p><p>We added the final rules: <em>“Duplicate charges, even small amounts, are always HIGH. Refund requests unresolved for more than a week are HIGH. A feature that worked before an update and now doesn’t is MEDIUM.”</em></p><pre>RESULTS - prompt v3<br>Structural:  20/20<br>Semantic:    20/20<br>Score:       100.0%</pre><pre>v2: 80.0%  →  v3: 100.0%  (delta: +20.0%)<br>→ Improved by +20.0% — safe to deploy</pre><p><strong>The full arc: 60% → 80% → 100%.</strong> Three prompt iterations, each driven entirely by what the eval harness told us to fix. No guessing. No “it looks fine to me.” Just a number, going up, with proof.</p><h3>Why three prompt versions — and why version them at all</h3><p>This is the part most people miss.</p><p><strong>What the versions are:</strong> v1, v2, and v3 are three iterations of the same prompt — each an attempt to make the classifier more accurate.</p><p><strong>Why three:</strong> because the first prompt is never the final prompt. v1 is your honest starting point. v2 and v3 are corrections, each fixing the specific, named failures the harness surfaced. You don’t decide the number in advance — you stop when the score is good enough.</p><p><strong>Why version them at all:</strong> every classification stored in the database records which prompt version produced it. Every eval run records its version too. Without versioning, a prompt change is invisible — you can’t tell whether you improved the system or quietly broke it. With versioning, the regression check can state plainly: <em>“v2 scored 80%, v3 scored 100%, the change is safe.”</em> The version number turns a vague “I think it’s better” into a measurable fact.</p><p><strong>How to test a new version:</strong> change the prompt file, bump the version number in config, run the eval harness. It loads the golden dataset, classifies all 20 cases, scores them, saves the result, and automatically compares it to the previous run. One command. One number. One verdict.</p><p>That loop — <em>change prompt → run eval → read the delta</em> — is the whole discipline of prompt engineering done properly.</p><h3>Test it yourself</h3><p>The classifier exposes one endpoint: POST /api/complaints. Sample requests for developers: <a href="http://localhost:9090/api/complaints">http://localhost:9090/api/complaints</a></p><p><strong>Fraud — expect BILLING / CRITICAL</strong></p><pre>{<br>  &quot;text&quot;: &quot;Someone made two unauthorized purchases on my card totaling $800. I did not approve these.&quot;,<br>  &quot;customerRef&quot;: &quot;CUST-001&quot;,<br>  &quot;source&quot;: &quot;email&quot;<br>}</pre><p><strong>Technical failure — expect TECHNICAL / HIGH</strong></p><pre>{<br>  &quot;text&quot;: &quot;The app crashes every time I open it. I reinstalled it twice and still cannot log in.&quot;,<br>  &quot;customerRef&quot;: &quot;CUST-002&quot;,<br>  &quot;source&quot;: &quot;chat&quot;<br>}</pre><p><strong>Phishing report — expect ACCOUNT / CRITICAL</strong></p><pre>{<br>  &quot;text&quot;: &quot;I received a suspicious email asking for my password and account number claiming to be from you.&quot;,<br>  &quot;customerRef&quot;: &quot;CUST-003&quot;,<br>  &quot;source&quot;: &quot;email&quot;<br>}</pre><p><strong>Minor issue — expect TECHNICAL / LOW</strong></p><pre>{<br>  &quot;text&quot;: &quot;Pages are loading a little slowly today. Not urgent, just mentioning it.&quot;,<br>  &quot;customerRef&quot;: &quot;CUST-004&quot;,<br>  &quot;source&quot;: &quot;form&quot;<br>}</pre><p><strong>Validation error — expect HTTP 400</strong></p><pre>{<br>  &quot;text&quot;: &quot;&quot;,<br>  &quot;customerRef&quot;: &quot;CUST-005&quot;,<br>  &quot;source&quot;: &quot;email&quot;<br>}</pre><p>Run the eval harness with a single command and you get the full graded report — score, failed cases, and the regression comparison against your last run.</p><h4>The Three Prompt Versions</h4><p>Here are the three prompt versions in full, so you can reproduce the exact evolution described in this article.</p><h4>Prompt v1 — starting point (60%)</h4><pre>You are an expert customer complaint classifier for a financial services company.<br>Your task is to analyze the customer complaint below and return a precise classification.<br><br>COMPLAINT:<br>{complaint}<br><br>---<br><br>CLASSIFICATION RULES:<br><br>CATEGORY - choose exactly one:<br>- BILLING    : incorrect charges, refund requests, invoice disputes, payment failures<br>- TECHNICAL  : app errors, login failures, system outages, feature bugs<br>- DELIVERY   : late delivery, missing order, wrong item received<br>- ACCOUNT    : account locked, password reset, data update requests, account closure,<br>               suspicious logins, phishing reports, possible data exposure<br>- OTHER      : does not fit any category above (e.g. general feedback or praise)<br><br>URGENCY - choose exactly one based on business and financial impact:<br>- LOW      : general question, minor inconvenience, no financial impact<br>- MEDIUM   : service degraded, customer waiting for resolution<br>- HIGH     : financial loss reported, service completely unavailable, deadline at risk<br>- CRITICAL : fraud suspected, data breach possible, regulatory deadline missed<br><br>SUGGESTED TEAM - choose exactly one from this list (use the exact text):<br>- &quot;Billing Support Team&quot;<br>- &quot;Technical Support Team&quot;<br>- &quot;Logistics Team&quot;<br>- &quot;Account Management Team&quot;<br>- &quot;General Support Team&quot;<br><br>REASONING - write exactly one sentence explaining your classification decision.<br><br>---<br><br>IMPORTANT RULES:<br>- When in doubt between two urgency levels, always choose the higher one.<br>- If the customer mentions fraud or unauthorized transactions, urgency is always CRITICAL.<br>- Base your decision only on what is written in the complaint.</pre><h4>Prompt v2 — first iteration (80%)</h4><p>What changed and why: the eval harness showed three failures — minor performance issues going to OTHER, password reset failures going to ACCOUNT, and urgency rules too vague. Added explicit examples per category, added the rule that technical failures blocking financial actions are HIGH, and clarified GDPR closures as MEDIUM.</p><pre>You are an expert customer complaint classifier for a financial services company.<br>Your task is to analyze the customer complaint below and return a precise classification.<br><br>COMPLAINT:<br>{complaint}<br><br>---<br><br>CLASSIFICATION RULES:<br><br>CATEGORY - choose exactly one:<br>- BILLING    : incorrect charges, refund requests, invoice disputes, payment failures,<br>               unauthorized transactions, fraud, duplicate charges<br>- TECHNICAL  : app errors, login failures, system outages, feature bugs,<br>               slow performance, data not loading, password reset failures,<br>               any system failure that prevents the user from completing an action<br>- DELIVERY   : late delivery, missing order, wrong item received, damaged package<br>- ACCOUNT    : account locked, password reset requests (not technical failures),<br>               personal data updates, account closure, suspicious logins,<br>               phishing reports, possible data exposure<br>- OTHER      : general feedback, praise, questions that do not describe a problem<br><br>URGENCY - choose exactly one based on business and financial impact:<br>- LOW      : general question, minor inconvenience, no financial impact,<br>             feedback or praise<br>- MEDIUM   : service degraded, customer waiting for resolution,<br>             account closure or GDPR deletion requests (regulatory obligation),<br>             wrong or damaged item received<br>- HIGH     : financial loss reported, service completely unavailable,<br>             financial data inconsistency between systems,<br>             delivery not received past the expected date,<br>             deadline at risk (e.g. payment due soon and system blocks access)<br>- CRITICAL : fraud suspected, unauthorized transactions reported,<br>             data breach possible, suspicious login from unknown location,<br>             phishing attempt reported<br><br>SUGGESTED TEAM - choose exactly one from this list (use the exact text):<br>- &quot;Billing Support Team&quot;<br>- &quot;Technical Support Team&quot;<br>- &quot;Logistics Team&quot;<br>- &quot;Account Management Team&quot;<br>- &quot;General Support Team&quot;<br><br>REASONING - write exactly one sentence explaining your classification decision.<br><br>---<br><br>IMPORTANT RULES:<br>- Unauthorized transactions and fraud are always BILLING + CRITICAL.<br>- If a technical failure is blocking a financial action, urgency is HIGH.<br>- Financial data inconsistency between platforms is always HIGH urgency.<br>- Slow performance or minor bugs with no financial impact are TECHNICAL + LOW.<br>- Account closure and GDPR deletion requests are always MEDIUM.<br>- When in doubt between two urgency levels, always choose the higher one.<br>- Base your decision only on what is written in the complaint.</pre><h4>Prompt v3 — final version (100%)</h4><p>What changed and why: four edge cases remained — duplicate charges not seen as financial loss, a billing inquiry with no complaint going to OTHER, an unresolved refund rated too low, and a feature regression after an update rated LOW. Added explicit rules for each.</p><pre>You are an expert customer complaint classifier for a financial services company.<br>Your task is to analyze the customer complaint below and return a precise classification.<br><br>COMPLAINT:<br>{complaint}<br><br>---<br><br>CLASSIFICATION RULES:<br><br>CATEGORY - choose exactly one:<br>- BILLING    : incorrect charges, refund requests, invoice disputes, payment failures,<br>               unauthorized transactions, fraud, duplicate charges,<br>               ANY billing question or inquiry even if no problem is described<br>- TECHNICAL  : app errors, login failures, system outages, feature bugs,<br>               slow performance, data not loading, password reset failures,<br>               feature regression (something that worked before and no longer works),<br>               any system failure that prevents the user from completing an action<br>- DELIVERY   : late delivery, missing order, wrong item received, damaged package<br>- ACCOUNT    : account locked, password reset requests (not technical failures),<br>               personal data updates, account closure, suspicious logins,<br>               phishing reports, possible data exposure<br>- OTHER      : general feedback, praise, questions that do not relate to billing,<br>               technical issues, delivery, or account management<br><br>URGENCY - choose exactly one based on business and financial impact:<br>- LOW      : general question, minor inconvenience, no financial impact,<br>             feedback or praise, slow performance with no financial consequence<br>- MEDIUM   : service degraded, customer waiting for resolution,<br>             account closure or GDPR deletion requests (regulatory obligation),<br>             wrong or damaged item received,<br>             feature regression after an update (worked before, broken now)<br>- HIGH     : financial loss reported, duplicate charges confirmed,<br>             refund not resolved after more than one week,<br>             financial data inconsistency between systems,<br>             service completely unavailable,<br>             delivery not received past the expected date,<br>             deadline at risk<br>- CRITICAL : fraud suspected, unauthorized transactions reported,<br>             data breach possible, suspicious login from unknown location,<br>             phishing attempt reported<br><br>SUGGESTED TEAM - choose exactly one from this list (use the exact text):<br>- &quot;Billing Support Team&quot;<br>- &quot;Technical Support Team&quot;<br>- &quot;Logistics Team&quot;<br>- &quot;Account Management Team&quot;<br>- &quot;General Support Team&quot;<br><br>REASONING - write exactly one sentence explaining your classification decision.<br><br>---<br><br>IMPORTANT RULES:<br>- Unauthorized transactions and fraud are always BILLING + CRITICAL.<br>- Duplicate charges, even small amounts, are always HIGH urgency.<br>- Refund requests unresolved for more than one week are always HIGH urgency.<br>- If a technical failure is blocking a financial action, urgency is HIGH.<br>- Financial data inconsistency between platforms is always HIGH urgency.<br>- A feature that worked before a recent update and now does not = MEDIUM urgency.<br>- Billing questions and inquiries, even with no complaint, are BILLING category.<br>- Account closure and GDPR deletion requests are always MEDIUM.<br>- Slow performance or minor bugs with no financial impact are TECHNICAL + LOW.<br>- When in doubt between two urgency levels, always choose the higher one.<br>- Base your decision only on what is written in the complaint.</pre><h4>How to use these versions yourself</h4><p>Two steps — nothing more.</p><p><strong>Step 1 — Copy the prompt content into </strong><strong>classifier-prompt.txt</strong></p><p>Each version above is the exact content of src/main/resources/prompts/classifier-prompt.txt. To test a specific version, copy its full content and replace what is currently in that file.</p><p><strong>Step 2 — Bump the version in config</strong></p><p>Open src/main/resources/application.yml and update:</p><pre>app:<br>  classifier:<br>    prompt-version: &quot;v2&quot;  # match the version you just copied in &quot;src/main/resources/prompts/classifier-prompt.txt&quot;</pre><p>Then run the eval harness:</p><pre>mvn test -Peval</pre><p>The harness classifies all 20 cases, scores them, and automatically compares the result against your previous run. Score went up — safe to deploy. Score went down — roll back the prompt and try again.</p><p><strong>Want a cleaner setup?</strong> Keep all three files separately as classifier-prompt-v1.txt, classifier-prompt-v2.txt, classifier-prompt-v3.txt, and make the filename configurable:</p><pre>app:<br>  classifier:<br>    prompt-version: &quot;v3&quot;<br>    prompt-file: &quot;prompts/classifier-prompt-v3.txt&quot;</pre><pre>@Value(&quot;classpath:${app.classifier.prompt-file}&quot;)<br>private Resource promptResource;</pre><p>Now switching versions is one line in config — no copy-pasting content.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*F2TocsY_O58iL3168PerlQ.jpeg" /></figure><h3>The takeaway</h3><p>A production AI feature is three things, not one. You <strong>build</strong> it, you <strong>tune the prompt</strong> until it’s reliable, and you <strong>evaluate</strong> it so you can prove that reliability with a number.</p><p>When you put an LLM behind a feature, your old tests stop meaning anything. A green build that only checks <em>“did it run”</em> tells you nothing about <em>“is it right.”</em> An eval harness fixes that — a golden dataset you write by hand, three checks, a score you can show a manager, and a versioned prompt history that proves every change made things better, not worse.</p><p>Autonomy isn’t the goal. <strong>Reliability is.</strong> And reliability is something you measure — or you don’t have it at all.</p><p>The full source code is available on <a href="https://github.com/bouguern/AI-complaint-classifier"><em>GitHub</em></a>.</p><p>Thank you.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=78ef812e1178" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building a new employees Onboarding AI Agent with Spring Boot 4, Spring AI 2.0,]]></title>
            <link>https://medium.com/@bouguern.mohamed/building-a-new-employees-onboarding-ai-agent-with-spring-boot-4-spring-ai-2-0-d9ad4bd6776f?source=rss-9126d0af0ba2------2</link>
            <guid isPermaLink="false">https://medium.com/p/d9ad4bd6776f</guid>
            <category><![CDATA[ai-agent]]></category>
            <category><![CDATA[ai-agent-development]]></category>
            <category><![CDATA[spring-ai]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[spring-boot]]></category>
            <dc:creator><![CDATA[Mohamed Bouguern]]></dc:creator>
            <pubDate>Fri, 15 May 2026 10:23:54 GMT</pubDate>
            <atom:updated>2026-05-23T09:02:37.443Z</atom:updated>
            <content:encoded><![CDATA[<h3>Building a new employees Onboarding AI Agent with Spring Boot 4, Spring AI 2.0, Java 21, tool calling, multi-turn memory and hexagonal architecture</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/974/1*ANc1x9HWCQBEtb0wr5FD8A.png" /></figure><p>I Built an Onboarding AI Agent in Java — No Python, No LangChain, Just Spring Boot 4 and Spring AI 2.0</p><p>Everyone says you need Python for AI. I built a production-pattern AI agent entirely in Java 21 + Spring Boot 4. Here’s exactly how it works.</p><h4>Why an Agent — Not a REST Controller?</h4><p>Before writing a single line of code, ask yourself: <strong>why does this need an agent?</strong></p><p>A regular REST controller could fetch a user profile and an onboarding schedule in 10 lines. So what makes this an agent?</p><p>The answer is one word: <strong>autonomy</strong>.</p><p>When a manager types:</p><pre>&quot;Prepare the full onboarding summary for Mohamed&quot;</pre><p>No hardcoded logic decides which data to fetch. The LLM reads the intent, decides which tools to call, calls them in the right order, and synthesizes the result. If the user only asks for the profile — only the profile tool fires. If they ask for the schedule — only the schedule tool fires. If they ask for both — both fire.</p><p>That decision logic is the agent. And it lives entirely in the LLM, not in your Java code.</p><h4>Why Spring AI Over LangChain4j?</h4><p>Both are strong. I chose Spring AI for one reason: it integrates natively with the Spring ecosystem.</p><p>`@Tool` annotations, `ChatClient`, and `MessageChatMemoryAdvisor` follow exactly the same patterns as Spring MVC and Spring Data. For a Spring Boot team, the developer experience is significantly smoother — tools are Spring beans, memory is an advisor, and the agent loop is a fluent API call.</p><p>LangChain4j is a strong alternative, especially if you need maximum provider flexibility or are not on Spring Boot. But for this project, Spring AI is the right fit.</p><h4>Architecture — Why Hexagonal?</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/803/1*ecOnd5hcFqdzK2t-q6Gbpw.png" /></figure><p>You might wonder why this project uses Hexagonal Architecture instead of a simple layered structure.</p><p>In this agent, the domain logic — resolving a user profile, fetching an onboarding schedule — must remain completely independent of how data is fetched or how the AI layer is wired. By defining outbound ports as interfaces and implementing them in the infrastructure layer, we can swap PostgreSQL for MongoDB, replace OpenAI with Ollama, or add a new tool without touching a single line of business logic.</p><p>More importantly, this structure scales naturally: <em>today we have two tools, but a real onboarding system could have ten — tool calling policies</em>, notification triggers, calendar integrations. Hexagonal architecture gives the agent room to grow without turning into a tightly coupled mess. Clean boundaries now means maintainable code later.</p><pre>presentation/           ← REST controllers, DTOs<br>application/            ← Use cases (interfaces) + Services (orchestration)<br>domain/                 ← Pure domain models + Outbound port interfaces<br>infrastructure/<br>  persistence/          ← JPA entities, Spring Data repos, adapters<br>  ai/tool/              ← @Tool-annotated Spring components<br>  ai/agent/             ← ChatClient wiring, system prompt, agent loop<br>config/                 ← Spring beans (ChatClient)</pre><h4>Tech Stack</h4><pre>|    Layer    |                  Technology                      |<br>|-------------|--------------------------------------------------|<br>| Language    |   Java 21                                        |<br>| Framework   |   Spring Boot 4.0                                |<br>| AI          |   Spring AI 2.0.0-M3 + Groq llama-3.1-8b-instant |<br>| Persistence |   PostgreSQL + Spring Data JPA                   |<br>| Migrations  |   Flyway 10                                      |<br>| Concurrency |   Java 21 Virtual Threads                        |</pre><h4>Step 1 — Project Setup</h4><pre>&lt;?xml version=&quot;1.0&quot; encoding=&quot;UTF-8&quot;?&gt;<br>&lt;project xmlns=&quot;http://maven.apache.org/POM/4.0.0&quot;<br> xmlns:xsi=&quot;http://www.w3.org/2001/XMLSchema-instance&quot;<br> xsi:schemaLocation=&quot;http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd&quot;&gt;<br> &lt;modelVersion&gt;4.0.0&lt;/modelVersion&gt;<br> &lt;parent&gt;<br>  &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt;<br>  &lt;artifactId&gt;spring-boot-starter-parent&lt;/artifactId&gt;<br>  &lt;version&gt;4.0.6&lt;/version&gt;<br>  &lt;relativePath /&gt; &lt;!-- lookup parent from repository --&gt;<br> &lt;/parent&gt;<br> &lt;groupId&gt;com.bouguern&lt;/groupId&gt;<br> &lt;artifactId&gt;onboarding-agent&lt;/artifactId&gt;<br> &lt;version&gt;0.0.1-SNAPSHOT&lt;/version&gt;<br> &lt;name&gt;onboarding-agent&lt;/name&gt;<br> &lt;description&gt;AI Onboarding Agent — Spring Boot 4 + Spring AI + Java 21&lt;/description&gt;<br><br> &lt;properties&gt;<br>  &lt;java.version&gt;21&lt;/java.version&gt;<br>  &lt;spring-ai.version&gt;2.0.0-M3&lt;/spring-ai.version&gt;<br> &lt;/properties&gt;<br><br> &lt;dependencies&gt;<br>  &lt;dependency&gt;<br>   &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt;<br>   &lt;artifactId&gt;spring-boot-starter-data-jpa&lt;/artifactId&gt;<br>  &lt;/dependency&gt;<br>  &lt;dependency&gt;<br>   &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt;<br>   &lt;artifactId&gt;spring-boot-starter-flyway&lt;/artifactId&gt;<br>  &lt;/dependency&gt;<br>  &lt;dependency&gt;<br>   &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt;<br>   &lt;artifactId&gt;spring-boot-starter-validation&lt;/artifactId&gt;<br>  &lt;/dependency&gt;<br>  &lt;dependency&gt;<br>   &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt;<br>   &lt;artifactId&gt;spring-boot-starter-webmvc&lt;/artifactId&gt;<br>  &lt;/dependency&gt;<br>  &lt;dependency&gt;<br>   &lt;groupId&gt;org.flywaydb&lt;/groupId&gt;<br>   &lt;artifactId&gt;flyway-database-postgresql&lt;/artifactId&gt;<br>  &lt;/dependency&gt;<br>  &lt;dependency&gt;<br>   &lt;groupId&gt;org.springframework.ai&lt;/groupId&gt;<br>   &lt;artifactId&gt;spring-ai-starter-model-openai&lt;/artifactId&gt;<br>  &lt;/dependency&gt;<br><br>  &lt;dependency&gt;<br>   &lt;groupId&gt;org.postgresql&lt;/groupId&gt;<br>   &lt;artifactId&gt;postgresql&lt;/artifactId&gt;<br>   &lt;scope&gt;runtime&lt;/scope&gt;<br>  &lt;/dependency&gt;<br>  &lt;!-- Flyway 10.x requires both jars for PostgreSQL --&gt;<br>  &lt;dependency&gt;<br>   &lt;groupId&gt;org.flywaydb&lt;/groupId&gt;<br>   &lt;artifactId&gt;flyway-core&lt;/artifactId&gt;<br>  &lt;/dependency&gt;<br>  &lt;dependency&gt;<br>   &lt;groupId&gt;org.flywaydb&lt;/groupId&gt;<br>   &lt;artifactId&gt;flyway-database-postgresql&lt;/artifactId&gt;<br>  &lt;/dependency&gt;<br><br>  &lt;dependency&gt;<br>   &lt;groupId&gt;org.projectlombok&lt;/groupId&gt;<br>   &lt;artifactId&gt;lombok&lt;/artifactId&gt;<br>   &lt;optional&gt;true&lt;/optional&gt;<br>  &lt;/dependency&gt;<br>  &lt;dependency&gt;<br>   &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt;<br>   &lt;artifactId&gt;spring-boot-starter-data-jpa-test&lt;/artifactId&gt;<br>   &lt;scope&gt;test&lt;/scope&gt;<br>  &lt;/dependency&gt;<br>  &lt;dependency&gt;<br>   &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt;<br>   &lt;artifactId&gt;spring-boot-starter-flyway-test&lt;/artifactId&gt;<br>   &lt;scope&gt;test&lt;/scope&gt;<br>  &lt;/dependency&gt;<br>  &lt;dependency&gt;<br>   &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt;<br>   &lt;artifactId&gt;spring-boot-starter-validation-test&lt;/artifactId&gt;<br>   &lt;scope&gt;test&lt;/scope&gt;<br>  &lt;/dependency&gt;<br>  &lt;dependency&gt;<br>   &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt;<br>   &lt;artifactId&gt;spring-boot-starter-webmvc-test&lt;/artifactId&gt;<br>   &lt;scope&gt;test&lt;/scope&gt;<br>  &lt;/dependency&gt;<br> &lt;/dependencies&gt;<br> &lt;dependencyManagement&gt;<br>  &lt;dependencies&gt;<br>   &lt;dependency&gt;<br>    &lt;groupId&gt;org.springframework.ai&lt;/groupId&gt;<br>    &lt;artifactId&gt;spring-ai-bom&lt;/artifactId&gt;<br>    &lt;version&gt;${spring-ai.version}&lt;/version&gt;<br>    &lt;type&gt;pom&lt;/type&gt;<br>    &lt;scope&gt;import&lt;/scope&gt;<br>   &lt;/dependency&gt;<br>  &lt;/dependencies&gt;<br> &lt;/dependencyManagement&gt;<br><br> &lt;repositories&gt;<br>  &lt;repository&gt;<br>   &lt;id&gt;spring-milestones&lt;/id&gt;<br>   &lt;name&gt;Spring Milestones&lt;/name&gt;<br>   &lt;url&gt;https://repo.spring.io/milestone&lt;/url&gt;<br>   &lt;snapshots&gt;<br>    &lt;enabled&gt;false&lt;/enabled&gt;<br>   &lt;/snapshots&gt;<br>  &lt;/repository&gt;<br> &lt;/repositories&gt;<br><br> &lt;pluginRepositories&gt;<br>  &lt;pluginRepository&gt;<br>   &lt;id&gt;spring-milestones&lt;/id&gt;<br>   &lt;name&gt;Spring Milestones&lt;/name&gt;<br>   &lt;url&gt;https://repo.spring.io/milestone&lt;/url&gt;<br>   &lt;snapshots&gt;<br>    &lt;enabled&gt;false&lt;/enabled&gt;<br>   &lt;/snapshots&gt;<br>  &lt;/pluginRepository&gt;<br> &lt;/pluginRepositories&gt;<br><br> &lt;build&gt;<br>  &lt;plugins&gt;<br>   &lt;plugin&gt;<br>    &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt;<br>    &lt;artifactId&gt;spring-boot-maven-plugin&lt;/artifactId&gt;<br>    &lt;configuration&gt;<br>     &lt;excludes&gt;<br>      &lt;exclude&gt;<br>       &lt;groupId&gt;org.projectlombok&lt;/groupId&gt;<br>       &lt;artifactId&gt;lombok&lt;/artifactId&gt;<br>      &lt;/exclude&gt;<br>     &lt;/excludes&gt;<br>    &lt;/configuration&gt;<br>   &lt;/plugin&gt;<br>   &lt;plugin&gt;<br>    &lt;groupId&gt;org.apache.maven.plugins&lt;/groupId&gt;<br>    &lt;artifactId&gt;maven-compiler-plugin&lt;/artifactId&gt;<br>    &lt;executions&gt;<br>     &lt;execution&gt;<br>      &lt;id&gt;default-compile&lt;/id&gt;<br>      &lt;phase&gt;compile&lt;/phase&gt;<br>      &lt;goals&gt;<br>       &lt;goal&gt;compile&lt;/goal&gt;<br>      &lt;/goals&gt;<br>      &lt;configuration&gt;<br>       &lt;annotationProcessorPaths&gt;<br>        &lt;path&gt;<br>         &lt;groupId&gt;org.projectlombok&lt;/groupId&gt;<br>         &lt;artifactId&gt;lombok&lt;/artifactId&gt;<br>        &lt;/path&gt;<br>       &lt;/annotationProcessorPaths&gt;<br>      &lt;/configuration&gt;<br>     &lt;/execution&gt;<br>     &lt;execution&gt;<br>      &lt;id&gt;default-testCompile&lt;/id&gt;<br>      &lt;phase&gt;test-compile&lt;/phase&gt;<br>      &lt;goals&gt;<br>       &lt;goal&gt;testCompile&lt;/goal&gt;<br>      &lt;/goals&gt;<br>      &lt;configuration&gt;<br>       &lt;annotationProcessorPaths&gt;<br>        &lt;path&gt;<br>         &lt;groupId&gt;org.projectlombok&lt;/groupId&gt;<br>         &lt;artifactId&gt;lombok&lt;/artifactId&gt;<br>        &lt;/path&gt;<br>       &lt;/annotationProcessorPaths&gt;<br>      &lt;/configuration&gt;<br>     &lt;/execution&gt;<br>    &lt;/executions&gt;<br>   &lt;/plugin&gt;<br>  &lt;/plugins&gt;<br> &lt;/build&gt;<br><br>&lt;/project&gt;</pre><p>Two notes worth highlighting:</p><p><strong>Spring AI 2.0.0-M3 requires Spring Boot 4.</strong> Spring AI 1.0 does not work with Spring Boot 4.x — the autoconfiguration classes simply do not exist. Spring AI 2.0 GA is scheduled for May 28, 2026. When it releases, update the version and remove the milestone repository.</p><p><strong>Flyway 10 requires two jars for PostgreSQL.</strong> `flyway-core` alone will throw `FlywayException: No database found` at startup. The `flyway-database-postgresql` jar is mandatory since Flyway 10 extracted database-specific support into separate modules.</p><h4>Step 2 — Configuration (application.properties)</h4><pre>spring.application.name=onboarding-agent<br>server.port=9090<br><br># Java 21 Virtual Threads<br>spring.threads.virtual.enabled=true<br><br># PostgreSQL<br>spring.datasource.url=jdbc:postgresql://localhost:5432/onboarding_db<br>spring.datasource.username=${DB_USERNAME}<br>spring.datasource.password=${DB_PASSWORD}<br>spring.datasource.driver-class-name=org.postgresql.Driver<br><br># JPA<br>spring.jpa.hibernate.ddl-auto=validate<br>spring.jpa.show-sql=false<br>spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.PostgreSQLDialect<br><br># Flyway<br>spring.flyway.enabled=true<br>spring.flyway.locations=classpath:db/migration<br><br># Spring AI — OpenAI<br>spring.ai.openai.api-key=${GROQ_API_KEY}<br>spring.ai.openai.base-url=https://api.groq.com/openai<br>spring.ai.openai.chat.options.model=llama-3.1-8b-instant<br>spring.ai.openai.chat.options.temperature=0.2<br><br># Logging<br>logging.level.com.bouguern.demo=DEBUG<br>logging.level.org.springframework.ai=DEBUG<br>logging.level.root=INFO</pre><h4>Step 3 — Database Schema</h4><p>`src/main/resources/db/migration/V1__init_schema.sql`</p><pre>DROP TABLE IF EXISTS onboarding_schedules;<br>DROP TABLE IF EXISTS users;<br><br>CREATE TABLE users (<br>    id          BIGSERIAL PRIMARY KEY,<br>    full_name   VARCHAR(100) NOT NULL,<br>    email       VARCHAR(150) NOT NULL UNIQUE,<br>    department  VARCHAR(100) NOT NULL,<br>    role        VARCHAR(100) NOT NULL,<br>    created_at  TIMESTAMP    NOT NULL DEFAULT NOW()<br>);<br><br>CREATE TABLE onboarding_schedules (<br>    id          BIGSERIAL PRIMARY KEY,<br>    user_id     BIGINT       NOT NULL REFERENCES users(id),<br>    plan_name   VARCHAR(150) NOT NULL,<br>    start_date  DATE         NOT NULL,<br>    end_date    DATE         NOT NULL,<br>    mentor_name VARCHAR(100) NOT NULL,<br>    status      VARCHAR(50)  NOT NULL DEFAULT &#39;PENDING&#39;,<br>    created_at  TIMESTAMP    NOT NULL DEFAULT NOW()<br>);<br><br>INSERT INTO users (full_name, email, department, role)<br>VALUES<br>    (&#39;Mohamed Salah&#39;,  &#39;mohamed.salah@company.com&#39;,  &#39;Engineering&#39;, &#39;Senior Java Developer&#39;),<br>    (&#39;Sofia Martinez&#39;, &#39;sofia.martinez@company.com&#39;, &#39;Product&#39;,     &#39;Product Manager&#39;),<br>    (&#39;Lucas Dupont&#39;,   &#39;lucas.dupont@company.com&#39;,   &#39;Engineering&#39;, &#39;DevOps Engineer&#39;);<br><br>INSERT INTO onboarding_schedules (user_id, plan_name, start_date, end_date, mentor_name, status)<br>VALUES<br>    (1, &#39;Backend Engineering Track&#39;, &#39;2025-06-01&#39;, &#39;2025-06-30&#39;, &#39;Karim Benali&#39;,   &#39;IN_PROGRESS&#39;),<br>    (2, &#39;Product Onboarding Track&#39;,  &#39;2025-06-05&#39;, &#39;2025-06-25&#39;, &#39;Emma Leclerc&#39;,   &#39;PENDING&#39;),<br>    (3, &#39;DevOps Foundation Track&#39;,   &#39;2025-06-10&#39;, &#39;2025-07-10&#39;, &#39;Youssef Amrani&#39;, &#39;PENDING&#39;);</pre><h4>Step 4 — Domain Layer</h4><p>The domain layer is pure Java. Zero framework dependencies — no JPA annotations, no Spring annotations, nothing. Just records and interfaces.</p><pre>public record UserProfile(<br>        Long id,<br>        String fullName,<br>        String email,<br>        String department,<br>        String role<br>) {}</pre><pre>public record OnboardingSchedule(<br>        Long id,<br>        Long userId,<br>        String planName,<br>        LocalDate startDate,<br>        LocalDate endDate,<br>        String mentorName,<br>        String status<br>) {}</pre><p>The outbound ports define what the application needs from any data source:</p><pre>public interface UserProfilePort {<br>    Optional&lt;UserProfile&gt; findByEmail(String email);<br>}<br><br>public interface OnboardingSchedulePort {<br>    Optional&lt;OnboardingSchedule&gt; findByUserId(Long userId);<br>}</pre><p>The domain never sees JPA. The infrastructure layer implements these interfaces. That is the core of hexagonal architecture.</p><h4>Step 5 — Application Layer</h4><p>The application layer orchestrates domain logic. It calls ports — never JPA repositories directly.</p><pre>@Slf4j<br>@Service<br>@RequiredArgsConstructor<br>public class UserProfileService implements GetUserProfileUseCase {<br><br>    private final UserProfilePort userProfilePort;<br><br>    @Override<br>    @Transactional(readOnly = true)<br>    public Optional&lt;UserProfile&gt; execute(String email) {<br>        log.debug(&quot;Fetching user profile for email: {}&quot;, email);<br>        return userProfilePort.findByEmail(email);<br>    }<br>}</pre><pre>@Slf4j<br>@Service<br>@RequiredArgsConstructor<br>public class OnboardingScheduleService implements GetOnboardingScheduleUseCase {<br><br>    private final UserProfilePort userProfilePort;<br>    private final OnboardingSchedulePort onboardingSchedulePort;<br><br>    @Override<br>    @Transactional(readOnly = true)<br>    public Optional&lt;OnboardingSchedule&gt; execute(String email) {<br>        var userOpt = userProfilePort.findByEmail(email);<br>        if (userOpt.isEmpty()) {<br>            log.warn(&quot;No user found for email: {} — cannot fetch schedule&quot;, email);<br>            return Optional.empty();<br>        }<br>        return onboardingSchedulePort.findByUserId(userOpt.get().id());<br>    }<br>}</pre><p>Notice that `OnboardingScheduleService` resolves the user first, then fetches the schedule. If the user does not exist, it returns empty gracefully — the agent tool handles the fallback message to the LLM. No exceptions, no 500 errors.</p><h4>Step 6 — Persistence Adapters</h4><p>JPA entities and adapters live entirely in the infrastructure layer. They never cross the adapter boundary.</p><pre>@Getter @Setter @NoArgsConstructor<br>@Entity<br>@Table(name = &quot;users&quot;, indexes = {<br>        @Index(name = &quot;idx_users_email&quot;, columnList = &quot;email&quot;, unique = true)<br>})<br>public class UserEntity {<br><br>    @Id<br>    @GeneratedValue(strategy = GenerationType.IDENTITY)<br>    private Long id;<br><br>    @Column(name = &quot;full_name&quot;, nullable = false, length = 100)<br>    private String fullName;<br><br>    @Column(nullable = false, unique = true, length = 150)<br>    private String email;<br><br>    @Column(nullable = false, length = 100)<br>    private String department;<br><br>    @Column(nullable = false, length = 100)<br>    private String role;<br><br>    @Column(name = &quot;created_at&quot;, nullable = false, updatable = false)<br>    private LocalDateTime createdAt;<br><br>    @PrePersist<br>    protected void onCreate() { this.createdAt = LocalDateTime.now(); }<br>}</pre><p>The adapter maps JPA entities to domain models — this is the anti-corruption layer:</p><pre>@Component<br>@RequiredArgsConstructor<br>public class UserProfileAdapter implements UserProfilePort {<br><br>    private final UserJpaRepository userJpaRepository;<br><br>    @Override<br>    public Optional&lt;UserProfile&gt; findByEmail(String email) {<br>        return userJpaRepository.findByEmail(email).map(this::toDomain);<br>    }<br><br>    private UserProfile toDomain(UserEntity e) {<br>        return new UserProfile(<br>                e.getId(), e.getFullName(), e.getEmail(),<br>                e.getDepartment(), e.getRole()<br>        );<br>    }<br>}</pre><h4>Step 7 — The Two Tools</h4><p>This is the most important section. Tools are the bridge between the LLM and your business logic.</p><p>Each `@Tool` method is a thin adapter — it calls a use case and formats the result as a string for the LLM. No business logic lives here.</p><pre>@Slf4j<br>@Component<br>@RequiredArgsConstructor<br>public class GetUserProfileTool {<br><br>    private final GetUserProfileUseCase getUserProfileUseCase;<br><br>    @Tool(name = &quot;getUserProfile&quot;, description = &quot;&quot;&quot;<br>            Retrieves an employee&#39;s full profile including full name, email,<br>            department, and role. Use when the user asks about an employee&#39;s<br>            identity, position, or contact information.<br>            Requires the employee&#39;s email address as input.<br>            &quot;&quot;&quot;)<br>    public String getUserProfile(<br>            @ToolParam(description = &quot;The employee&#39;s email address&quot;) String email) {<br><br>        log.info(&quot;[TOOL INVOKED] getUserProfile — email: {}&quot;, email);<br><br>        return getUserProfileUseCase.execute(email)<br>                .map(this::formatProfile)<br>                .orElse(&quot;No employee profile found for email: %s. Please verify and try again.&quot;<br>                        .formatted(email));<br>    }<br><br>    private String formatProfile(UserProfile p) {<br>        return &quot;&quot;&quot;<br>                Employee Profile:<br>                - Full Name  : %s<br>                - Email      : %s<br>                - Department : %s<br>                - Role       : %s<br>                &quot;&quot;&quot;.formatted(p.fullName(), p.email(), p.department(), p.role());<br>    }<br>}</pre><pre>@Slf4j<br>@Component<br>@RequiredArgsConstructor<br>public class GetOnboardingScheduleTool {<br><br>    private final GetOnboardingScheduleUseCase getOnboardingScheduleUseCase;<br><br>    @Tool(name = &quot;getOnboardingSchedule&quot;, description = &quot;&quot;&quot;<br>            Retrieves an employee&#39;s onboarding schedule including plan name,<br>            start date, end date, assigned mentor, and current status.<br>            Use when the user asks about onboarding timelines, plans,<br>            mentors, or schedule details.<br>            Requires the employee&#39;s email address as input.<br>            &quot;&quot;&quot;)<br>    public String getOnboardingSchedule(<br>            @ToolParam(description = &quot;The employee&#39;s email address&quot;) String email) {<br><br>        log.info(&quot;[TOOL INVOKED] getOnboardingSchedule — email: {}&quot;, email);<br><br>        return getOnboardingScheduleUseCase.execute(email)<br>                .map(this::formatSchedule)<br>                .orElse(&quot;No onboarding schedule found for email: %s.&quot;<br>                        .formatted(email));<br>    }<br><br>    private String formatSchedule(OnboardingSchedule s) {<br>        return &quot;&quot;&quot;<br>                Onboarding Schedule:<br>                - Plan        : %s<br>                - Start Date  : %s<br>                - End Date    : %s<br>                - Mentor      : %s<br>                - Status      : %s<br>                &quot;&quot;&quot;.formatted(s.planName(), s.startDate(), s.endDate(),<br>                s.mentorName(), s.status());<br>    }<br>}</pre><p>Two things to notice:</p><p>The `@Tool` description is critical. The LLM reads it to decide when to call each tool. Write it like documentation for the model, not for a human developer.</p><p>The `orElse` fallback returns a human-readable string — not an exception. The LLM receives it, understands it, and informs the user gracefully. This is how you implement graceful degradation in an agent.</p><h4>Step 8 — The Agent</h4><p>This is the core of the entire project.</p><pre>@Slf4j<br>@Component<br>@RequiredArgsConstructor<br>public class OnboardingAgent {<br><br>    private static final String SYSTEM_PROMPT = &quot;&quot;&quot;<br>            You are an intelligent Onboarding Assistant for a software company.<br>            You help HR managers and team leads retrieve employee onboarding information.<br><br>            You have access to two tools:<br>            - getUserProfile: retrieves full name, email, department, and role.<br>            - getOnboardingSchedule: retrieves onboarding plan, dates, mentor, and status.<br><br>            Guidelines:<br>            - Always ask for the employee&#39;s email if not provided.<br>            - Use only the tools relevant to what the user is asking.<br>            - If a tool returns a not-found message, inform the user clearly.<br>            - ALWAYS display the full data returned by the tool in your response.<br>            - NEVER summarize or confirm — show the actual values.<br>            - Be structured and professional in your responses.<br>            &quot;&quot;&quot;;<br><br>    private final ChatClient chatClient;<br>    private final GetUserProfileTool getUserProfileTool;<br>    private final GetOnboardingScheduleTool getOnboardingScheduleTool;<br><br>    /**<br>     * ⚠️  IN-MEMORY — demo/dev only.<br>     *<br>     * Production limitation:<br>     * - History is LOST on restart<br>     * - Does NOT work across multiple instances<br>     * - No TTL — memory grows unbounded under load<br>     *<br>     * Production alternatives (swap InMemoryChatMemoryRepository only):<br>     * - JDBC/PostgreSQL → spring-ai-model-chat-memory-repository-jdbc<br>     * - Redis           → spring-ai-model-chat-memory-repository-redis<br>     *<br>     * Only this field changes — all other layers are unaffected.<br>     */<br>    private final MessageChatMemoryAdvisor memoryAdvisor =<br>            MessageChatMemoryAdvisor.builder(<br>                    MessageWindowChatMemory.builder()<br>                            .chatMemoryRepository(new InMemoryChatMemoryRepository())<br>                            .maxMessages(20)<br>                            .build()<br>            ).build();<br><br>    public String chat(String userMessage, String sessionId) {<br>        log.info(&quot;[AGENT] Processing — session: {} | message: {}&quot;, sessionId, userMessage);<br><br>        String response = chatClient.prompt()<br>                .system(SYSTEM_PROMPT)<br>                .user(userMessage)<br>                .advisors(advisor -&gt; advisor.param(ChatMemory.CONVERSATION_ID, sessionId))<br>                .advisors(memoryAdvisor)<br>                .tools(getUserProfileTool, getOnboardingScheduleTool)<br>                .call()<br>                .content();<br><br>        log.info(&quot;[AGENT] Response ready — session: {}&quot;, sessionId);<br>        return response;<br>    }<br>}</pre><p>Four things happening here worth explaining:</p><p><strong>System prompt</strong> defines the agent’s persona, available tools, and strict output rules. The LLM reads this on every request.</p><p><strong>`CONVERSATION_ID` param</strong> passes the session identifier to the memory advisor. Each session has isolated history — User A’s conversation never bleeds into User B’s.</p><p><strong>`memoryAdvisor`</strong> maintains up to 20 messages per session. On each request, the full history is sent to the LLM so it can reason across turns.</p><p><strong>`.tools(getUserProfileTool, getOnboardingScheduleTool)`</strong> registers the tools. The LLM sees their names and descriptions and decides autonomously which ones to call.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/757/1*VkBm2ItrHlKSpHkM0BlIdg.png" /></figure><h4>Step 9 — REST Controller</h4><pre>@Slf4j<br>@RestController<br>@RequestMapping(&quot;/api/v1/agent&quot;)<br>@RequiredArgsConstructor<br>public class OnboardingAgentController {<br><br>    private final OnboardingAgent onboardingAgent;<br><br>    @PostMapping(&quot;/chat&quot;)<br>    public ResponseEntity&lt;AgentChatResponse&gt; chat(<br>            @Valid @RequestBody AgentChatRequest request,<br>            HttpSession httpSession) {<br><br>        /*<br>         * DEMO: session ID derived from the HTTP session (server-owned).<br>         * Each Postman/browser session gets its own isolated conversation history.<br>         *<br>         * PRODUCTION: replace with the authenticated user&#39;s identity from JWT —<br>         * never trust a sessionId coming from the request body.<br>         *<br>         * String sessionId = SecurityContextHolder.getContext()<br>         *         .getAuthentication().getName();<br>         */<br>        String sessionId = httpSession.getId();<br><br>        log.info(&quot;[REST] Incoming agent request — session: {}&quot;, sessionId);<br>        String agentResponse = onboardingAgent.chat(request.message(), sessionId);<br>        return ResponseEntity.ok(AgentChatResponse.of(sessionId, agentResponse));<br>    }<br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/492/1*ADpYDtTVOcmICt6E0J1-vA.png" /></figure><p>Notice the session comment. In this demo the session ID comes from the HTTP session — server-owned, not client-controlled. In production it should come from the authenticated user’s JWT token. This one comment shows senior readers you understand the security boundary.</p><h4>Virtual Threads — One Line, Big Impact</h4><pre>spring.threads.virtual.enabled=true</pre><p>Every tool call blocks on DB I/O. In a traditional thread-per-request model, each blocked call holds a platform thread — expensive and limited. With Java 21 virtual threads, the JVM parks the virtual thread cheaply when it blocks, frees the carrier thread, and resumes when the DB responds.</p><p>The result: your agent can handle hundreds of concurrent sessions on the same hardware without thread exhaustion. One property, zero code changes.</p><h4>The Demo — 3 Prompts, 3 Behaviors</h4><p>Send all requests to <strong>`POST http://localhost:9090/api/v1/agent/chat`</strong> with <strong>`Content-Type: application/json`</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/609/1*9oe3hA8-e7atEjVjYQB1Gg.png" /></figure><p><strong><em>Prompt 1 — only `getUserProfile` fires:</em></strong></p><pre>{ &quot;message&quot;: &quot;Get me the profile for mohamed.salah@company.com&quot; }</pre><p><strong><em>Prompt 2 — only `getOnboardingSchedule` fires:</em></strong></p><pre>{ &quot;message&quot;: &quot;What is the onboarding schedule for mohamed.salah@company.com?&quot; }</pre><p><strong><em>Prompt 3— both tools fire in sequence:</em></strong></p><pre>{ &quot;message&quot;: &quot;Prepare the full onboarding summary for mohamed.salah@company.com&quot; }</pre><p><strong><em>Prompt 4 — memory test, send after Prompt 1 in the same Postman tab:</em></strong></p><pre>{ &quot;message&quot;: &quot;What is his onboarding schedule?&quot; }</pre><p><strong><em>Prompt 4</em></strong> is the most revealing one. The agent knows “his” refers to Mohamed from the previous turn — without the user repeating the email. That is multi-turn memory working through <strong>`MessageWindowChatMemory`</strong> and <strong>`CONVERSATION_ID`</strong> isolation.</p><h4>Graceful Degradation</h4><p>When a tool cannot find data, it returns a descriptive string instead of throwing an exception:</p><pre>.orElse(&quot;No employee profile found for email: %s. Please verify and try again.&quot;<br>        .formatted(email));</pre><p>The LLM receives this string, understands it as a not-found signal, and informs the user naturally. Test it:</p><pre>{ &quot;message&quot;: &quot;Get me the profile for unknown@company.com&quot; }</pre><p>The agent responds gracefully — no stack trace, no 500 error, no confusing technical message.</p><h4>Security Note</h4><p>This article deliberately omits JWT authentication to stay focused on the agent pattern. In production, two things must change.</p><p>First, the session ID must be derived from the authenticated user’s identity — not from the HTTP session. Anyone who can send a request can currently access any conversation history by reusing a session cookie.</p><p>Second, tool access must be scoped per user. A tool that queries the database has access to all rows. In production, the query must be filtered by the authenticated user’s permissions — a manager should only see employees in their department.</p><p>Both are standard Spring Security patterns and deserve their own article.</p><h4>Conclusion</h4><p>A Java developer does not need Python to build production-pattern AI agents in 2026.</p><p>Spring AI 2.0 on Spring Boot 4 gives you <strong><em>`@Tool</em></strong>` annotations, <strong><em>`ChatClient`</em></strong>, memory management, and multi-provider support — all following the same patterns of Spring MVC and Spring Data.</p><p>The architecture shown here is not a tutorial toy. Hexagonal ports and adapters, clean domain models, use case interfaces, thin tool adapters, graceful degradation, server-owned sessions, and virtual thread concurrency — these are the patterns production teams use.</p><p>The only difference between this demo and a real onboarding system is scale: more tools, JWT authentication, Redis memory, and a proper security layer. The foundation is identical.</p><p>Full source code available on <a href="https://github.com/bouguern/onboarding-agent"><strong>GitHub</strong></a>. Spring AI 2.0 GA releases May 28, 2026 — update the version and remove the milestone repository when it does.</p><p><em>Follow me on Medium for more articles. Connect with me on LinkedIn: </em><a href="https://www.linkedin.com/in/mohamed-bouguern/"><em>LinkedIn Profile</em></a></p><p>Thank you.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d9ad4bd6776f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Designing a Production-Ready AI Chat Service with Spring Boot, LangChain4j, Ollama, and Hexagonal…]]></title>
            <link>https://medium.com/@bouguern.mohamed/designing-a-production-ready-ai-chat-service-with-spring-boot-langchain4j-ollama-and-hexagonal-d5cf11d61bb8?source=rss-9126d0af0ba2------2</link>
            <guid isPermaLink="false">https://medium.com/p/d5cf11d61bb8</guid>
            <category><![CDATA[spring-boot]]></category>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[ollama]]></category>
            <category><![CDATA[langchain4j]]></category>
            <dc:creator><![CDATA[Mohamed Bouguern]]></dc:creator>
            <pubDate>Fri, 08 May 2026 10:38:57 GMT</pubDate>
            <atom:updated>2026-05-23T09:05:46.161Z</atom:updated>
            <content:encoded><![CDATA[<h3>Designing a Production-Ready AI Chat Service with Spring Boot, LangChain4j, Ollama, and Hexagonal Architecture</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ObyRFvNxSrjf3MQ6GNtKnA.jpeg" /></figure><p>I’ve read a lot of “Build an AI chatbot in Java” tutorials lately.</p><p>They all follow the same pattern: add one dependency, call an API, print the response. Thirty lines of code, a GitHub repo with no tests, and a README that just says “run Main.java.”</p><p>That’s not a production service. That’s a demo.</p><p>The difference matters more than you think. A demo works once, on your laptop, with your specific setup. A production service handles concurrent users, fails gracefully when the AI provider is down, maintains conversation history correctly across multiple turns, and can swap AI providers without a rewrite.</p><p>This article builds the real thing.</p><h4>What we’re building</h4><p>A stateful conversational AI service using <strong>Spring Boot 3</strong>, <strong>LangChain4j 0.31</strong>, and <strong>Ollama</strong> — running a local LLM completely on your machine. No API keys. No usage costs. No data leaving your infrastructure.</p><p>The service:</p><ul><li>Accepts user messages over a REST API</li><li>Maintains full conversation history across multiple turns — the AI actually remembers what you said before</li><li>Returns structured RFC 7807 error responses instead of raw stack traces</li><li>Exposes LLM latency metrics via Micrometer and Prometheus</li><li>Can swap AI providers by writing a single new adapter class</li></ul><p>By the end you have a running service with 31 passing tests.</p><h4>The architectural decision that changes everything</h4><p>Before writing a single class, I asked one question: <strong>where does </strong><strong>dev.langchain4j get imported?</strong></p><p>In most tutorials, LangChain4j imports show up everywhere — in controllers, in services, scattered across the codebase. When LangChain4j releases a breaking change (and it has, multiple times), you’re hunting through everything.</p><p>In this service, LangChain4j imports exist in exactly one package: infrastructure.ai. The domain layer has zero knowledge of it. The application layer has zero knowledge of it. They communicate through a port:</p><pre>public interface LanguageModelPort {<br>    String generate(Conversation conversation);<br>}</pre><p>That’s it. The domain says: <em>I need something that turns a Conversation into a String.</em> It doesn’t care if that’s Ollama, GPT-4, or a mock in a test. This is hexagonal architecture in practice — not as a theory you read about, but as a constraint you enforce in your package structure.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*o41sw0JhEvaYh0Jzj1rYSw.jpeg" /></figure><h4>Architecture overview</h4><p>The service has four strict layers. Each one has exactly one job. None of them reach into the layer above.</p><pre>API Layer<br>  ChatController · GlobalExceptionHandler · DTOs<br>        ↓ calls inbound port<br><br>Application Layer<br>  ChatUseCaseImpl — orchestration only<br><br>        ↓ calls outbound ports<br><br>Domain Layer  (pure Java — zero framework imports)<br>  Conversation · ChatMessage · ConversationDomainService<br>  ChatUseCase · LanguageModelPort · ConversationRepository<br><br>        ↓ implemented by<br><br>Infrastructure Layer<br>  OllamaAdapter · InMemoryConversationRepository<br>  LangChain4jConfig · DomainConfig<br>        ↓<br>  Ollama (Docker) — local LLM on port 11434</pre><p>The dependency rule: every arrow points inward. Infrastructure depends on the domain. The domain depends on nothing.</p><pre>src/main/java/bouguern/langchain4j/demo/<br>│<br>├── AiChatServiceApplication.java<br>│<br>├── domain/                          # Pure Java — zero framework imports<br>│   ├── model/<br>│   │   ├── Conversation.java        # Aggregate root<br>│   │   ├── ChatMessage.java         # Value object (record)<br>│   │   ├── ConversationId.java      # Value object — no primitive obsession<br>│   │   ├── MessageRole.java         # Enum: USER · ASSISTANT · SYSTEM<br>│   │   ├── ChatCommand.java         # Inbound domain command<br>│   │   └── ChatResult.java          # Outbound domain result<br>│   ├── port/<br>│   │   ├── inbound/<br>│   │   │   └── ChatUseCase.java     # Inbound port (interface)<br>│   │   └── outbound/<br>│   │       ├── LanguageModelPort.java     # AI provider contract<br>│   │       └── ConversationRepository.java # Persistence contract<br>│   ├── service/<br>│   │   └── ConversationDomainService.java # Context window · validation<br>│   └── exception/<br>│       ├── ConversationNotFoundException.java<br>│       ├── InvalidConversationStateException.java<br>│       └── LanguageModelException.java<br>│<br>├── application/<br>│   └── usecase/<br>│       └── ChatUseCaseImpl.java     # Orchestration: resolve→validate→generate→save<br>│<br>├── infrastructure/<br>│   ├── ai/<br>│   │   ├── OllamaAdapter.java       # LangChain4j implementation of LanguageModelPort<br>│   │   └── OllamaPromptConstants.java<br>│   ├── persistence/<br>│   │   └── InMemoryConversationRepository.java  # Replaced by Redis in Day 5<br>│   └── config/<br>│       ├── LangChain4jConfig.java   # OllamaChatModel bean wiring<br>│       └── DomainConfig.java        # Wires pure-Java domain services<br>│<br>└── api/<br>    ├── dto/<br>    │   ├── ChatRequest.java         # Inbound HTTP body (record)<br>    │   └── ChatResponse.java        # Outbound HTTP body (record)<br>    └── rest/<br>        ├── ChatController.java      # Thin — maps DTOs, delegates to use case<br>        └── GlobalExceptionHandler.java  # RFC 7807 ProblemDetail</pre><h4>Tech stack</h4><pre>Concern          Technology<br><br>Language      :   Java 21<br>Framework     :   Spring Boot 3.3.0<br>AI library    :   LangChain4j 0.31.0<br>LLM runtime   :   Ollama (Docker)<br>LLM model     :   llama3.2<br>Metrics       :   Micrometer + Prometheus<br>Build         :   Maven</pre><h4>Project setup</h4><p>Check the <em>pom.xml, application.yml</em>, and <em>docker-compose.yml</em> files in the repository.</p><h4>Domain layer — pure Java, zero framework</h4><p>The domain layer has no Spring annotations, no LangChain4j imports, no Jakarta dependencies. It compiles and runs as plain Java. This is non-negotiable.</p><p><strong>ConversationId — fighting primitive obsession</strong></p><pre>public record ConversationId(String value) {<br><br>    public ConversationId {<br>        Objects.requireNonNull(value, &quot;ConversationId must not be null&quot;);<br>        if (value.isBlank()) {<br>            throw new IllegalArgumentException(&quot;ConversationId must not be blank&quot;);<br>        }<br>    }<br><br>    public static ConversationId generate() {<br>        return new ConversationId(UUID.randomUUID().toString());<br>    }<br><br>    public static ConversationId of(String value) {<br>        return new ConversationId(value);<br>    }<br>}</pre><p>You might wonder why not just use String. Consider this method signature:</p><pre>void load(String userId, String conversationId) // compiler cannot help you<br>void load(UserId userId, ConversationId conversationId) // swap = compile error</pre><p>One record class eliminates an entire category of runtime bugs.</p><p><strong>ChatMessage — immutable by design</strong></p><pre>public record ChatMessage(<br>        MessageRole role,<br>        String content,<br>        Instant timestamp<br>) {<br>    public ChatMessage {<br>        Objects.requireNonNull(role, &quot;role must not be null&quot;);<br>        Objects.requireNonNull(content, &quot;content must not be null&quot;);<br>        Objects.requireNonNull(timestamp, &quot;timestamp must not be null&quot;);<br>        if (content.isBlank()) {<br>            throw new IllegalArgumentException(&quot;Message content must not be blank&quot;);<br>        }<br>    }<br><br>    public static ChatMessage userMessage(String content) {<br>        return new ChatMessage(MessageRole.USER, content, Instant.now());<br>    }<br><br>    public static ChatMessage assistantMessage(String content) {<br>        return new ChatMessage(MessageRole.ASSISTANT, content, Instant.now());<br>    }<br>}</pre><p>Once a message is recorded it must never change. Records enforce this — there are no setters. The factory methods make intent clear at the call site.</p><p><strong>Conversation — the aggregate root</strong></p><pre>public class Conversation {<br><br>    private final ConversationId id;<br>    private final List&lt;ChatMessage&gt; messages;<br>    private final Instant createdAt;<br>    private Instant updatedAt;<br><br>    public Conversation(ConversationId id) {<br>        this.id        = Objects.requireNonNull(id, &quot;id must not be null&quot;);<br>        this.messages  = new ArrayList&lt;&gt;();<br>        this.createdAt = Instant.now();<br>        this.updatedAt = this.createdAt;<br>    }<br><br>    public void addMessage(ChatMessage message) {<br>        Objects.requireNonNull(message, &quot;message must not be null&quot;);<br>        messages.add(message);<br>        updatedAt = Instant.now();<br>    }<br><br>    public List&lt;ChatMessage&gt; getMessages() {<br>        return Collections.unmodifiableList(messages);<br>    }<br><br>    public ConversationId getId()  { return id; }<br>    public Instant getCreatedAt()  { return createdAt; }<br>    public Instant getUpdatedAt()  { return updatedAt; }<br>}</pre><p>Two things to notice. First, addMessage is the only mutation allowed. No setMessages(). History is append-only. Second, getMessages() returns an unmodifiable view — callers cannot manipulate history by holding a reference to the list. The aggregate owns its invariants.</p><p><strong>The ports — your escape hatches</strong></p><pre>// Inbound — what the API layer calls<br>public interface ChatUseCase {<br>    ChatResult chat(ChatCommand command);<br>}<br><br>// Outbound — what the domain needs from AI<br>public interface LanguageModelPort {<br>    String generate(Conversation conversation);<br>}<br><br>// Outbound — what the domain needs from persistence<br>public interface ConversationRepository {<br>    void save(Conversation conversation);<br>    Optional&lt;Conversation&gt; findById(ConversationId id);<br>}</pre><p>Today LanguageModelPort is implemented by OllamaAdapter. Tomorrow you write OpenAiAdapter. The domain never changes — you write one class and register it.</p><p><strong>Why ChatCommand and ChatResult exist</strong></p><pre>public record ChatCommand(String conversationId, String userMessage) {<br>    public boolean hasConversationId() {<br>        return conversationId != null &amp;&amp; !conversationId.isBlank();<br>    }<br>}<br><br>public record ChatResult(<br>        String conversationId,<br>        String assistantMessage,<br>        long messageCount<br>) {}</pre><p>ChatUseCase is a domain port. If it accepted ChatRequest (an api.dto class), the domain layer would import from the API layer — a dependency pointing the wrong direction. ChatCommand and ChatResult are the domain&#39;s own input and output contracts. The controller maps ChatRequest → ChatCommand before calling the port, and ChatResult → ChatResponse after.</p><p><strong>The domain service — where real business logic lives</strong></p><pre>public class ConversationDomainService {<br><br>    private final int maxHistorySize;<br><br>    public ConversationDomainService(int maxHistorySize) {<br>        if (maxHistorySize &lt; 1) {<br>            throw new IllegalArgumentException(&quot;maxHistorySize must be at least 1&quot;);<br>        }<br>        this.maxHistorySize = maxHistorySize;<br>    }<br><br>    public List&lt;ChatMessage&gt; getContextWindow(Conversation conversation) {<br>        List&lt;ChatMessage&gt; all = conversation.getMessages();<br><br>        if (all.size() &lt;= maxHistorySize) {<br>            return new ArrayList&lt;&gt;(all);<br>        }<br><br>        boolean hasSystemHeader =<br>                !all.isEmpty() &amp;&amp; all.get(0).role() == MessageRole.SYSTEM;<br><br>        List&lt;ChatMessage&gt; window = new ArrayList&lt;&gt;();<br>        if (hasSystemHeader) {<br>            window.add(all.get(0));<br>            int from = all.size() - (maxHistorySize - 1);<br>            window.addAll(all.subList(from, all.size()));<br>        } else {<br>            int from = all.size() - maxHistorySize;<br>            window.addAll(all.subList(from, all.size()));<br>        }<br>        return window;<br>    }<br><br>    public void validateReadyForUserMessage(Conversation conversation) {<br>        List&lt;ChatMessage&gt; messages = conversation.getMessages();<br>        if (messages.isEmpty()) return;<br><br>        ChatMessage last = messages.get(messages.size() - 1);<br>        if (last.role() == MessageRole.USER) {<br>            throw new InvalidConversationStateException(<br>                    &quot;Cannot send: previous message in conversation [&quot;<br>                    + conversation.getId().value() + &quot;] has not been answered yet.&quot;);<br>        }<br>    }<br>}</pre><p>Two rules. Both are business decisions, not infrastructure decisions.</p><p>The context window rule: every message sent to Ollama costs processing time. A 200-message conversation history would take forever to process. We cap at 20 messages per request, always preserving the system prompt at index 0 so the assistant’s persona is never lost mid-conversation.</p><p>The validation rule: two consecutive user messages without an intervening assistant reply creates an ambiguous history that models handle badly, often skipping the first question silently. We catch this before it reaches Ollama.</p><p><strong>This validation must happen BEFORE </strong><strong>addMessage() is called.</strong> If you call it after, the last message is always USER — the check is permanently dead code. I&#39;ve seen this exact bug in several production codebases.</p><p><strong>Application layer — orchestration only</strong></p><pre>@Service<br>public class ChatUseCaseImpl implements ChatUseCase {<br><br>    private static final Logger log =<br>            LoggerFactory.getLogger(ChatUseCaseImpl.class);<br><br>    private final LanguageModelPort       languageModelPort;<br>    private final ConversationRepository  conversationRepository;<br>    private final ConversationDomainService domainService;<br><br>    public ChatUseCaseImpl(<br>            LanguageModelPort languageModelPort,<br>            ConversationRepository conversationRepository,<br>            ConversationDomainService domainService) {<br>        this.languageModelPort      = languageModelPort;<br>        this.conversationRepository = conversationRepository;<br>        this.domainService          = domainService;<br>    }<br><br>    @Override<br>    public ChatResult chat(ChatCommand command) {<br>        log.info(&quot;Chat request [conversationId={}]&quot;,<br>                command.hasConversationId() ? command.conversationId() : &quot;new&quot;);<br><br>        // 1. Resolve — load existing or create new<br>        Conversation conversation = resolveConversation(command);<br><br>        // 2. Validate BEFORE mutation — order is critical<br>        domainService.validateReadyForUserMessage(conversation);<br><br>        // 3. Record the user&#39;s message<br>        conversation.addMessage(ChatMessage.userMessage(command.userMessage()));<br><br>        // 4. Generate — adapter handles all provider details<br>        String aiReply = generateWithErrorTranslation(conversation);<br><br>        // 5. Record the assistant&#39;s reply<br>        conversation.addMessage(ChatMessage.assistantMessage(aiReply));<br><br>        // 6. Persist<br>        conversationRepository.save(conversation);<br><br>        log.info(&quot;Chat complete [conversationId={}, messages={}]&quot;,<br>                conversation.getId().value(),<br>                conversation.getMessages().size());<br><br>        return new ChatResult(<br>                conversation.getId().value(),<br>                aiReply,<br>                conversation.getMessages().size()<br>        );<br>    }<br><br>    private Conversation resolveConversation(ChatCommand command) {<br>        if (!command.hasConversationId()) {<br>            return new Conversation(ConversationId.generate());<br>        }<br>        return conversationRepository<br>                .findById(ConversationId.of(command.conversationId()))<br>                .orElseThrow(() -&gt;<br>                        new ConversationNotFoundException(command.conversationId()));<br>    }<br><br>    private String generateWithErrorTranslation(Conversation conversation) {<br>        try {<br>            return languageModelPort.generate(conversation);<br>        } catch (LanguageModelException e) {<br>            throw e;<br>        } catch (Exception e) {<br>            log.error(&quot;Unexpected failure [conversationId={}]&quot;,<br>                    conversation.getId().value(), e);<br>            throw new LanguageModelException(&quot;Failed to generate AI response&quot;, e);<br>        }<br>    }<br>}</pre><p>This class has zero business logic and zero infrastructure knowledge. It sequences operations and delegates everything. That’s its entire purpose.</p><p>Notice that resolveConversation throws a 404 when an unknown conversationId is provided. Many tutorials silently create a new conversation on an unknown ID. That hides client bugs — stale IDs, wrong environments, copy-paste errors. A 404 surfaces the problem immediately.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*p6JV-IxTbecKJdnh6U724w.jpeg" /></figure><h4>Infrastructure layer — where LangChain4j finally appears</h4><p><strong>OllamaAdapter</strong></p><pre>@Component<br>public class OllamaAdapter implements LanguageModelPort {<br><br>    private static final Logger log =<br>            LoggerFactory.getLogger(OllamaAdapter.class);<br><br>    private final ChatLanguageModel       chatLanguageModel;<br>    private final ConversationDomainService domainService;<br>    private final Timer                   llmTimer;<br>    private final String                  modelName;<br><br>    public OllamaAdapter(<br>            ChatLanguageModel chatLanguageModel,<br>            ConversationDomainService domainService,<br>            MeterRegistry meterRegistry,<br>            @Qualifier(&quot;ollamaModelName&quot;) String modelName) {<br>        this.chatLanguageModel = chatLanguageModel;<br>        this.domainService     = domainService;<br>        this.modelName         = modelName;<br>        this.llmTimer = Timer.builder(&quot;ai.llm.request.duration&quot;)<br>                .description(&quot;LLM generation request latency&quot;)<br>                .tag(&quot;model&quot;, modelName)<br>                .register(meterRegistry);<br>    }<br><br>    @Override<br>    public String generate(Conversation conversation) {<br>        List&lt;domain.ChatMessage&gt; context =<br>                domainService.getContextWindow(conversation);<br>        List&lt;ChatMessage&gt; messages = buildMessages(context);<br><br>        Timer.Sample sample = Timer.start();<br>        try {<br>            Response&lt;AiMessage&gt; response =<br>                    chatLanguageModel.generate(messages);<br>            String text = response.content().text();<br><br>            if (text == null || text.isBlank()) {<br>                throw new LanguageModelException(<br>                        &quot;Model returned empty response [conversationId=&quot;<br>                        + conversation.getId().value() + &quot;]&quot;);<br>            }<br>            return text;<br><br>        } catch (LanguageModelException e) {<br>            throw e;<br>        } catch (Exception e) {<br>            throw new LanguageModelException(<br>                    &quot;Ollama call failed [conversationId=&quot;<br>                    + conversation.getId().value() + &quot;]&quot;, e);<br>        } finally {<br>            sample.stop(llmTimer);<br>        }<br>    }<br><br>    private List&lt;ChatMessage&gt; buildMessages(List&lt;domain.ChatMessage&gt; domain) {<br>        List&lt;ChatMessage&gt; messages = new ArrayList&lt;&gt;(domain.size() + 1);<br><br>        boolean hasSystem = !domain.isEmpty()<br>                &amp;&amp; domain.get(0).role() == MessageRole.SYSTEM;<br>        if (!hasSystem) {<br>            messages.add(SystemMessage.from(OllamaPromptConstants.SYSTEM_PROMPT));<br>        }<br><br>        for (domain.ChatMessage msg : domain) {<br>            messages.add(switch (msg.role()) {<br>                case USER      -&gt; UserMessage.from(msg.content());<br>                case ASSISTANT -&gt; AiMessage.from(msg.content());<br>                case SYSTEM    -&gt; SystemMessage.from(msg.content());<br>            });<br>        }<br>        return messages;<br>    }<br>}</pre><p>Four things worth noting here.</p><p><strong>Naming collision handled deliberately.</strong> LangChain4j exports dev.langchain4j.data.message.ChatMessage. Our domain exports com.yourname.aichat.domain.model.ChatMessage. We import the LangChain4j one by short name and reference the domain one with its fully-qualified path. The boundary is visible at every line.</p><p><strong>Timer built once in constructor.</strong> Building Timer.builder() inside the generate() method would allocate unnecessary objects on every AI call. The timer is registered once, reused forever.</p><p><strong>Guard against empty responses.</strong> If Ollama returns blank text, we throw explicitly rather than silently saving an empty assistant message to the conversation history.</p><p><strong>Switch expression is exhaustive.</strong> Java 21’s switch on an enum is a compile-time guarantee — if you add a new MessageRole variant and forget to handle it here, the build fails.</p><p><strong>LangChain4jConfig</strong></p><pre>@Configuration<br>public class LangChain4jConfig {<br><br>    private final String ollamaBaseUrl;<br>    private final String modelName;<br>    private final int    numPredict;<br>    private final double temperature;<br>    private final int    timeoutSeconds;<br><br>    public LangChain4jConfig(<br>            @Value(&quot;${app.ai.ollama.base-url}&quot;)        String ollamaBaseUrl,<br>            @Value(&quot;${app.ai.ollama.model-name}&quot;)      String modelName,<br>            @Value(&quot;${app.ai.ollama.num-predict}&quot;)     int numPredict,<br>            @Value(&quot;${app.ai.ollama.temperature}&quot;)     double temperature,<br>            @Value(&quot;${app.ai.ollama.timeout-seconds}&quot;) int timeoutSeconds) {<br>        this.ollamaBaseUrl  = ollamaBaseUrl;<br>        this.modelName      = modelName;<br>        this.numPredict     = numPredict;<br>        this.temperature    = temperature;<br>        this.timeoutSeconds = timeoutSeconds;<br>    }<br><br>    @Bean<br>    public ChatLanguageModel chatLanguageModel() {<br>        return OllamaChatModel.builder()<br>                .baseUrl(ollamaBaseUrl)<br>                .modelName(modelName)<br>                .numPredict(numPredict)<br>                .temperature(temperature)<br>                .timeout(Duration.ofSeconds(timeoutSeconds))<br>                .build();<br>    }<br><br>    @Bean(name = &quot;ollamaModelName&quot;)<br>    public String ollamaModelName() {<br>        return modelName;<br>    }<br>}</pre><p>One important note: in LangChain4j 0.31.0, OllamaChatModel.builder() uses .numPredict(), not .maxTokens(). The method .maxTokens() does not exist on this builder and will cause a compile error. This is a real bug I&#39;ve seen in copy-pasted tutorials.</p><p><strong>DomainConfig — the bridge pattern</strong></p><pre>@Configuration<br>public class DomainConfig {<br><br>    @Bean<br>    public ConversationDomainService conversationDomainService(<br>            @Value(&quot;${app.conversation.max-history-size}&quot;) int maxHistorySize) {<br>        return new ConversationDomainService(maxHistorySize);<br>    }<br>}</pre><p>ConversationDomainService is pure Java with no Spring annotations. This @Configuration class reads application.yml and passes the value to the domain service constructor. Domain defines the logic. Infrastructure wires it into the container. Clean separation.</p><h4>API layer — three jobs only</h4><pre>@RestController<br>@RequestMapping(&quot;/api/v1&quot;)<br>public class ChatController {<br><br>    private static final Logger log =<br>            LoggerFactory.getLogger(ChatController.class);<br><br>    private final ChatUseCase chatUseCase;<br><br>    public ChatController(ChatUseCase chatUseCase) {<br>        this.chatUseCase = chatUseCase;<br>    }<br><br>    @PostMapping(&quot;/chat&quot;)<br>    public ResponseEntity&lt;ChatResponse&gt; chat(<br>            @Valid @RequestBody ChatRequest request) {<br>        log.info(&quot;POST /api/v1/chat [conversationId={}]&quot;,<br>                request.conversationId() != null<br>                        ? request.conversationId() : &quot;new&quot;);<br><br>        ChatResult result = chatUseCase.chat(<br>                new ChatCommand(request.conversationId(), request.message())<br>        );<br><br>        return ResponseEntity.ok(new ChatResponse(<br>                result.conversationId(),<br>                result.assistantMessage(),<br>                result.messageCount()<br>        ));<br>    }<br>}</pre><p>Three jobs. Validate input. Map ChatRequest → ChatCommand. Map ChatResult → ChatResponse. Nothing else. The controller doesn&#39;t know what a Conversation is. It doesn&#39;t know what Ollama is. It depends on ChatUseCase — the interface — never on ChatUseCaseImpl.</p><p><strong>Error handling that actually helps clients</strong></p><pre>@RestControllerAdvice<br>public class GlobalExceptionHandler {<br><br>    @ExceptionHandler(ConversationNotFoundException.class)<br>    public ProblemDetail handleNotFound(ConversationNotFoundException ex) {<br>        log.warn(&quot;Conversation not found [id={}]&quot;, ex.getConversationId());<br>        ProblemDetail pd = ProblemDetail<br>                .forStatusAndDetail(HttpStatus.NOT_FOUND, ex.getMessage());<br>        pd.setType(URI.create(&quot;/errors/conversation-not-found&quot;));<br>        pd.setTitle(&quot;Conversation Not Found&quot;);<br>        return pd;<br>    }<br><br>    @ExceptionHandler(LanguageModelException.class)<br>    public ProblemDetail handleLlmFailure(LanguageModelException ex) {<br>        log.error(&quot;Language model failure: {}&quot;, ex.getMessage(), ex);<br>        ProblemDetail pd = ProblemDetail.forStatusAndDetail(<br>                HttpStatus.SERVICE_UNAVAILABLE,<br>                &quot;The AI service is temporarily unavailable. Please retry.&quot;);<br>        pd.setType(URI.create(&quot;/errors/language-model-unavailable&quot;));<br>        pd.setTitle(&quot;AI Service Unavailable&quot;);<br>        return pd;<br>    }<br>}</pre><p>Most Spring services return {&quot;timestamp&quot;:&quot;...&quot;,&quot;status&quot;:500,&quot;error&quot;:&quot;Internal Server Error&quot;} when something goes wrong. That tells nobody anything actionable.</p><p>RFC 7807 ProblemDetail is built into Spring 6. The type field is a URI — clients switch on it programmatically. Operations teams grep logs by it. Log levels are intentional: 404 and 409 are log.warn() (client sent bad data, not our problem). 503 is log.error() (our infrastructure is broken, an alert should fire).</p><h4>Let’s run it</h4><pre># Start Ollama and pull llama3.2 (first run takes a few minutes)<br>docker compose up ollama -d<br>docker compose logs -f ollama-pull<br># Wait for: success<br><br># Start the Spring Boot service<br>./mvnw spring-boot:run<br><br># Start a new conversation<br>curl -s -X POST http://localhost:8890/api/v1/chat \<br>  -H &quot;Content-Type: application/json&quot; \<br>  -d &#39;{&quot;message&quot;:&quot;What is hexagonal architecture?&quot;}&#39; | jq .</pre><p><strong>Response:</strong></p><pre>{<br>  &quot;conversationId&quot;: &quot;f47ac10b-58cc-4372-a567-0e02b2c3d479&quot;,<br>  &quot;message&quot;: &quot;Hexagonal architecture, also called Ports and Adapters...&quot;,<br>  &quot;messageCount&quot;: 2<br>}</pre><pre># Continue — the AI remembers the previous question<br>curl -s -X POST http://localhost:8890/api/v1/chat \<br>  -H &quot;Content-Type: application/json&quot; \<br>  -d &#39;{<br>    &quot;conversationId&quot;: &quot;f47ac10b-58cc-4372-a567-0e02b2c3d479&quot;,<br>    &quot;message&quot;: &quot;Give me a Java code example&quot;<br>  }&#39; | jq .<br><br># Test 404 — unknown conversationId<br>curl -s -X POST http://localhost:8890/api/v1/chat \<br>  -H &quot;Content-Type: application/json&quot; \<br>  -d &#39;{&quot;conversationId&quot;:&quot;ghost&quot;,&quot;message&quot;:&quot;hi&quot;}&#39; | jq .<br># → {&quot;type&quot;:&quot;/errors/conversation-not-found&quot;,&quot;status&quot;:404,...}<br><br># Check LLM latency metrics<br>curl -s http://localhost:8890/actuator/prometheus | grep ai_llm<br># → ai_llm_request_duration_seconds_count{model=&quot;llama3.2:1b&quot;}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uB0z6zKeo-PfxQZFjW4t1Q.jpeg" /></figure><h4>Testing strategy</h4><p>We have zero Spring context loaded — all pure unit tests.</p><pre>@ExtendWith(MockitoExtension.class)<br>class ChatUseCaseImplTest {<br><br>    @Mock LanguageModelPort      languageModelPort;<br>    @Mock ConversationRepository conversationRepository;<br><br>    // Real domain service — never mock domain logic in use-case tests<br>    ConversationDomainService domainService;<br>    ChatUseCaseImpl           useCase;<br><br>    @BeforeEach<br>    void setUp() {<br>        domainService = new ConversationDomainService(20);<br>        useCase = new ChatUseCaseImpl(<br>                languageModelPort, conversationRepository, domainService);<br>    }<br><br>    @Test<br>    void chat_newConversation_returnsReply() {<br>        when(languageModelPort.generate(any())).thenReturn(&quot;Hello from AI&quot;);<br><br>        ChatResult result = useCase.chat(new ChatCommand(null, &quot;Hello&quot;));<br><br>        assertThat(result.assistantMessage()).isEqualTo(&quot;Hello from AI&quot;);<br>        assertThat(result.messageCount()).isEqualTo(2);<br>        verify(conversationRepository).save(any(Conversation.class));<br>    }<br><br>    @Test<br>    void chat_unknownConversationId_throws404() {<br>        when(conversationRepository.findById(any()))<br>                .thenReturn(Optional.empty());<br><br>        assertThatThrownBy(() -&gt;<br>                useCase.chat(new ChatCommand(&quot;unknown&quot;, &quot;hi&quot;)))<br>                .isInstanceOf(ConversationNotFoundException.class);<br>    }<br>}</pre><p>The domain service is instantiated directly — new ConversationDomainService(20). No mocking. Domain rules must run for real in application-layer tests. If you mock ConversationDomainService, you&#39;re testing that the use case calls a method — you&#39;re not testing that the domain rule actually works.</p><pre>./mvnw test<br># Expected: BUILD SUCCESS — 2 tests, 0 failures</pre><p>The complete source code is available on GitHub: <a href="https://github.com/bouguern/ai-chat-service.git"><strong><em>Repository</em></strong></a></p><p>Follow me on Medium for more articles. Connect with me on LinkedIn: <a href="https://www.linkedin.com/in/mohamed-bouguern/"><strong><em>LinkedIn Profile</em></strong></a></p><p>Thank you.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d5cf11d61bb8" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Smart REST API with AI Semantic Validation using Java 21, Spring Boot and Spring AI Starter Model…]]></title>
            <link>https://medium.com/@bouguern.mohamed/smart-rest-api-with-ai-semantic-validation-using-java-21-spring-boot-and-spring-ai-starter-model-25b504172396?source=rss-9126d0af0ba2------2</link>
            <guid isPermaLink="false">https://medium.com/p/25b504172396</guid>
            <category><![CDATA[javaai]]></category>
            <category><![CDATA[spring-ai-tutorial]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[spring-boot]]></category>
            <category><![CDATA[spring-ai]]></category>
            <dc:creator><![CDATA[Mohamed Bouguern]]></dc:creator>
            <pubDate>Thu, 07 May 2026 12:01:14 GMT</pubDate>
            <atom:updated>2026-05-07T12:01:14.230Z</atom:updated>
            <content:encoded><![CDATA[<h3><strong>Smart REST API with AI Semantic Validation using Java 21, Spring Boot and Spring AI Starter Model OpenAI</strong></h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/691/1*_-vLyf7LM4LLFtBD9vGuDA.png" /></figure><p>Every Java developer knows the standard validation toolkit. You add <strong>@NotBlank </strong>to ensure a field is not empty. You add <strong>@Email</strong> to check the format. You add <strong>@Size</strong> to enforce length limits. It works. It is fast. It is free.</p><p>But it has a fundamental blind spot.</p><p>Consider these values submitted to a job application API:</p><pre>fullName:            &quot;123abc$$&quot;<br>jobTitle:            &quot;I like eating pizza&quot;<br>professionalSummary: &quot;aaaaaaaaaaaaaaaaaaa&quot;</pre><p>Every single one passes standard Bean Validation. None of them should.</p><p>This is the difference between <strong>syntactic validation</strong> and <strong>semantic validation</strong>. Classical annotations check format. They have no concept of meaning. They cannot tell you whether a value makes sense in context — only whether it matches a pattern.</p><p>In this article, we build a production-grade Spring Boot 3 API that sends the entire DTO to an AI model in a single call and gets back a structured validation result. No per-field annotation engine. No reflection at request time. No hardcoded field names. Works on any DTO without writing a single extra class.</p><p>The full source code is available on GitHub: <a href="https://github.com/bouguern/smart-validation.git">Repository</a></p><h4>What We Are Building</h4><p>A REST endpoint that accepts job application submissions with two validation layers running in sequence.</p><p><strong>Layer 1 — Bean Validation</strong> runs first, always. It checks presence, format, and length. Free, instant, in-memory. If it fails, the request is rejected immediately with 400 Bad Request and the AI is never called.</p><p><strong>Layer 2 — AI Semantic Validation</strong> runs only if Layer 1 passes. The entire DTO is serialized to JSON and sent to Groq’s Llama 3.3 70B in a single API call. The model returns a flat map of field names to validation results. If any field fails, the request is rejected with 422 Unprocessable Entity.</p><p>The key architectural insight: <strong>AI validation complements classical validation — it never replaces it.</strong> Email format does not need AI. Whether a professional summary is coherent absolutely does.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/735/1*XyL4SChuAntEBLJa1zxJGA.png" /></figure><h4>Tech Stack</h4><ul><li>Java 21</li><li>Spring Boot 3.3.6</li><li>Spring AI 1.0.0</li><li>Groq API — Llama 3.3 70B (free tier, no credit card required)</li><li>Maven</li></ul><h4>Project Structure</h4><pre>src/main/java/blog/bouguern/smartvalidation/<br>├── SmartValidationApplication.java<br>├── config/<br>│   └── SpringAiConfig.java<br>├── validation/<br>│   ├── AiValidator.java<br>│   ├── AiValidatorImpl.java<br>│   └── AiValidationResponse.java<br>├── dto/<br>│   └── JobApplicationDTO.java<br>├── service/<br>│   └── JobApplicationService.java<br>├── controller/<br>│   └── JobApplicationController.java<br>└── exception/<br>    ├── AiValidationException.java<br>    ├── ValidationErrorResponse.java<br>    └── GlobalExceptionHandler.java</pre><h4>Step 1: See the pom.xml file in the Repo.</h4><p>We use spring-ai-starter-model-openai — not because we are using OpenAI, but because Groq implements the exact same API protocol. Spring AI&#39;s abstraction lets us point the same starter at any OpenAI-compatible provider by changing one URL in configuration. Zero code changes.</p><h4>Step 2: Configuration of application.yml</h4><pre>server:<br>  port: 8981  # change to any port you want<br><br>spring:<br>  application:<br>    name: smart-validation<br><br>  ai:<br>    openai:<br>      api-key: ${GROQ_API_KEY}<br>      base-url: https://api.groq.com/openai<br>      chat:<br>        options:<br>          model: llama-3.3-70b-versatile<br>          temperature: 0.0<br>          max-tokens: 150<br><br>app:<br>  validation:<br>    default-confidence-threshold: 0.80<br>    fallback-on-ai-failure: true<br>    timeout-ms: 5000 # Groq is fast but give 5s to be safe<br><br>logging:<br>  level:<br>    blog.bouguern.smartvalidation: DEBUG<br>    org.springframework.ai: INFO</pre><p>Two decisions deserve attention.</p><p>temperature: 0.0 makes AI responses deterministic. The same input always produces the same output. For validation, consistency is non-negotiable. If your API randomly accepts or rejects the same value depending on the AI&#39;s mood, users will lose trust immediately.</p><p>fallback-on-ai-failure: true means that when Groq is unavailable, requests pass through instead of being blocked. In production you might set this to false for strict environments.</p><p>To get your free Groq API key, go to console.groq.com, sign up, and generate a key. No credit card required. Then set it as an environment variable.</p><h4>Step 3: Spring AI Configuration</h4><p>Spring AI auto-configures ChatClient.Builder but not ChatClient itself. We build the ChatClient bean here and inject a default system prompt that applies to every AI call made through this instance. This reduces per-call prompt size and therefore token cost.</p><pre>package blog.bouguern.smartvalidation.config;<br><br>import org.springframework.ai.chat.client.ChatClient;<br>import org.springframework.context.annotation.Bean;<br>import org.springframework.context.annotation.Configuration;<br><br>@Configuration<br>public class SpringAiConfig {<br><br>    @Bean<br>    public ChatClient chatClient(ChatClient.Builder builder) {<br>        return builder<br>                .defaultSystem(&quot;&quot;&quot;<br>                        You are a strict semantic validation assistant for a professional API.<br>                        Always respond with valid JSON only.<br>                        Never add markdown or any text outside the JSON object.<br>                        &quot;&quot;&quot;)<br>                .build();<br>    }<br>}</pre><h4>Step 4: The Validation Response Record</h4><p>We use a Java record with a Map&lt;String, String&gt; instead of a list. This gives direct field lookup (fieldErrors.get(&quot;fullName&quot;)) instead of having to stream through a list. We store only the errors — the success case carries an empty map, which is clean and cheap.</p><p>The ok() and failed() factory methods make call sites read like plain English. List.copyOf() ensures the map passed in by the caller cannot be mutated after the exception is created.</p><pre>package blog.bouguern.smartvalidation.validation;<br><br>import java.util.Map;<br><br>public record AiValidationResponse(<br>        Map&lt;String, String&gt; fieldErrors,<br>        boolean             valid<br>) {<br><br>    public static AiValidationResponse ok() {<br>        return new AiValidationResponse(Map.of(), true);<br>    }<br><br>    public static AiValidationResponse failed(Map&lt;String, String&gt; fieldErrors) {<br>        return new AiValidationResponse(Map.copyOf(fieldErrors), false);<br>    }<br><br>    public boolean isValid() {<br>        return valid;<br>    }<br>}</pre><h4>Step 5: The Validator Interface</h4><p>Programming to an interface is the Dependency Inversion Principle applied. Today the implementation calls Groq. Tomorrow it could call Gemini, Mistral, or a self-hosted Ollama model. The service, controller, and every test depend on this interface — swapping providers requires only a new implementation class and a Spring bean swap. Nothing else changes.</p><pre>package blog.bouguern.smartvalidation.validation;<br><br>public interface AiValidator {<br><br>    AiValidationResponse validate(Object dto);<br>}</pre><h4>Step 6: The Validator Implementation</h4><p>This is the heart of the application. Four methods, each with one responsibility.</p><pre>package blog.bouguern.smartvalidation.validation;<br><br>import com.fasterxml.jackson.core.type.TypeReference;<br>import com.fasterxml.jackson.databind.ObjectMapper;<br>import lombok.extern.slf4j.Slf4j;<br>import org.springframework.ai.chat.client.ChatClient;<br>import org.springframework.beans.factory.annotation.Value;<br>import org.springframework.stereotype.Component;<br><br>import java.util.Map;<br>import java.util.concurrent.CompletableFuture;<br>import java.util.concurrent.ExecutionException;<br>import java.util.concurrent.TimeUnit;<br>import java.util.concurrent.TimeoutException;<br>import java.util.stream.Collectors;<br><br>@Slf4j<br>@Component<br>public class AiValidatorImpl implements AiValidator {<br><br>    private final ChatClient   chatClient;<br>    private final ObjectMapper objectMapper;<br>    private final long         timeoutMs;<br>    private final boolean      fallbackOnAiFailure;<br><br>    public AiValidatorImpl(<br>            ChatClient chatClient,<br>            ObjectMapper objectMapper,<br>            @Value(&quot;${app.validation.timeout-ms:5000}&quot;) long timeoutMs,<br>            @Value(&quot;${app.validation.fallback-on-ai-failure:true}&quot;) boolean fallbackOnAiFailure<br>    ) {<br>        this.chatClient          = chatClient;<br>        this.objectMapper        = objectMapper;<br>        this.timeoutMs           = timeoutMs;<br>        this.fallbackOnAiFailure = fallbackOnAiFailure;<br>    }<br><br>    @Override<br>    public AiValidationResponse validate(Object dto) {<br>        try {<br>            String dtoJson = objectMapper.writeValueAsString(dto);<br>            String prompt  = buildPrompt(dtoJson, dto);<br>            String raw     = callAi(prompt);<br><br>            log.debug(&quot;AI raw response: {}&quot;, raw);<br><br>            return parseResponse(raw);<br><br>        } catch (Exception e) {<br>            return handleFailure(e);<br>        }<br>    }<br><br>    private String buildPrompt(String dtoJson, Object dto) {<br>        String example = buildExample(dto);<br>        return &quot;&quot;&quot;<br>                Validate every field in the following JSON object semantically.<br><br>                Rules:<br>                - Reject random characters, gibberish, offensive or placeholder content<br>                - Reject values that do not make sense for their field name<br>                - Accept values that are coherent and contextually appropriate<br>                - For email fields: check semantic coherence only, not format<br><br>                JSON to validate:<br>                %s<br><br>                Respond ONLY with a flat JSON object where:<br>                - Each key is a field name from the input<br>                - Each value is &quot;OK&quot; if the field is valid or null<br>                - Each value is a short error message if the field is invalid<br><br>                Example response structure (your keys must match the input fields):<br>                %s<br><br>                No markdown. No explanation. Only the JSON object.<br>                &quot;&quot;&quot;.formatted(sanitize(dtoJson), example);<br>    }<br><br>    private String buildExample(Object dto) {<br>        java.lang.reflect.Field[] fields = dto.getClass().getDeclaredFields();<br>        String fieldLines = java.util.Arrays.stream(fields)<br>                .filter(f -&gt; !f.isSynthetic())<br>                .filter(f -&gt; !java.lang.reflect.Modifier.isStatic(f.getModifiers()))<br>                .map(f -&gt; &quot;  \&quot;&quot; + f.getName() + &quot;\&quot;: \&quot;OK or error message\&quot;&quot;)<br>                .collect(Collectors.joining(&quot;,\n&quot;));<br>        return &quot;{\n&quot; + fieldLines + &quot;\n}&quot;;<br>    }<br><br>    private String callAi(String prompt) {<br>        try {<br>            CompletableFuture&lt;String&gt; future = CompletableFuture.supplyAsync(<br>                    () -&gt; chatClient.prompt().user(prompt).call().content()<br>            );<br><br>            String response = future.get(timeoutMs, TimeUnit.MILLISECONDS);<br><br>            if (response == null || response.isBlank()) {<br>                throw new IllegalStateException(&quot;AI returned empty response&quot;);<br>            }<br><br>            return response;<br><br>        } catch (TimeoutException e) {<br>            throw new RuntimeException(&quot;AI timed out after &quot; + timeoutMs + &quot;ms&quot;, e);<br>        } catch (InterruptedException e) {<br>            Thread.currentThread().interrupt();<br>            throw new RuntimeException(&quot;AI call interrupted&quot;, e);<br>        } catch (ExecutionException e) {<br>            throw new RuntimeException(e.getCause().getMessage(), e.getCause());<br>        }<br>    }<br><br>    private AiValidationResponse parseResponse(String raw) throws Exception {<br>        String cleaned = raw.substring(<br>                raw.indexOf(&#39;{&#39;), raw.lastIndexOf(&#39;}&#39;) + 1<br>        );<br><br>        Map&lt;String, String&gt; results = objectMapper.readValue(<br>                cleaned, new TypeReference&lt;&gt;() {}<br>        );<br><br>        Map&lt;String, String&gt; errors = results.entrySet().stream()<br>                .filter(e -&gt; !&quot;OK&quot;.equalsIgnoreCase(e.getValue()))<br>                .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue));<br><br>        return errors.isEmpty()<br>                ? AiValidationResponse.ok()<br>                : AiValidationResponse.failed(errors);<br>    }<br><br>    private String sanitize(String value) {<br>        if (value == null) return &quot;&quot;;<br>        return value<br>                .replace(&quot;\\&quot;, &quot;\\\\&quot;)<br>                .replace(&quot;\&quot;&quot;, &quot;&#39;&quot;)<br>                .trim()<br>                .substring(0, Math.min(value.length(), 2000));<br>    }<br><br>    private AiValidationResponse handleFailure(Exception e) {<br>        log.warn(&quot;AI validation failed: {}&quot;, e.getMessage());<br>        return fallbackOnAiFailure<br>                ? AiValidationResponse.ok()<br>                : AiValidationResponse.failed(<br>                        Map.of(&quot;*&quot;, &quot;AI validation service unavailable — please try again later&quot;)<br>                  );<br>    }<br>}</pre><p>Four decisions in this class deserve explanation.</p><p>buildExample() generates the expected response structure dynamically from the DTO&#39;s actual fields using reflection. This means the prompt is never hardcoded for a specific DTO — change the DTO and the prompt adapts automatically. Add a new field and the AI knows to validate it on the next request.</p><p>callAi() wraps the Spring AI call in a CompletableFuture with a configurable timeout. Without a timeout, a slow or hanging Groq request blocks a servlet thread indefinitely. Under load this exhausts the thread pool in seconds and causes cascading failures. We restore the interrupt flag when catching InterruptedException — swallowing it is a common mistake that breaks thread lifecycle management.</p><p>parseResponse() uses indexOf(&#39;{&#39;) and lastIndexOf(&#39;}&#39;) to extract JSON. AI models occasionally add explanatory text before or after the JSON object despite explicit instructions. This makes parsing robust against any surrounding text.</p><p>sanitize() escapes characters that could break the JSON structure or inject instructions into the prompt. This is not just clean code — it is a security measure against prompt injection attacks.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/803/1*Q0QwwWfdTvnMd4OptmTtKw.png" /></figure><h4>Step 7: The DTO</h4><p>No @AiValidated annotations. The AI understands field semantics from field names alone — fullName, jobTitle, professionalSummary. We keep @NotBlank, @Email, and @Size because format validation must never depend on an external service.</p><pre>package blog.bouguern.smartvalidation.dto;<br><br>import jakarta.validation.constraints.Email;<br>import jakarta.validation.constraints.NotBlank;<br>import jakarta.validation.constraints.Size;<br>import lombok.Data;<br><br>@Data<br>public class JobApplicationDTO {<br><br>    @NotBlank(message = &quot;Full name is required&quot;)<br>    private String fullName;<br><br>    @NotBlank(message = &quot;Job title is required&quot;)<br>    private String jobTitle;<br><br>    @NotBlank(message = &quot;Email is required&quot;)<br>    @Email(message = &quot;Must be a valid email address&quot;)<br>    private String email;<br><br>    @NotBlank(message = &quot;Professional summary is required&quot;)<br>    @Size(min = 50, max = 500, message = &quot;Summary must be between 50 and 500 characters&quot;)<br>    private String professionalSummary;<br><br>    private String linkedInUrl;<br>}</pre><h4>Step 8: Exceptions and Error Response</h4><pre>package blog.bouguern.smartvalidation.exception;<br><br>import blog.bouguern.smartvalidation.validation.AiValidationResponse;<br>import lombok.Getter;<br><br>@Getter<br>public class AiValidationException extends RuntimeException {<br><br>    private final AiValidationResponse validationResponse;<br><br>    public AiValidationException(AiValidationResponse validationResponse) {<br>        super(&quot;AI semantic validation failed&quot;);<br>        this.validationResponse = validationResponse;<br>    }<br>}</pre><pre>package blog.bouguern.smartvalidation.exception;<br><br>import java.time.Instant;<br>import java.util.List;<br><br>public record ValidationErrorResponse(<br>        Instant          timestamp,<br>        int              status,<br>        String           error,<br>        String           path,<br>        List&lt;FieldError&gt; fieldErrors<br>) {<br>    public record FieldError(<br>            String field,<br>            String message<br>    ) {}<br>}</pre><pre>package blog.bouguern.smartvalidation.exception;<br><br>import jakarta.servlet.http.HttpServletRequest;<br>import lombok.extern.slf4j.Slf4j;<br>import org.springframework.http.HttpStatus;<br>import org.springframework.http.ResponseEntity;<br>import org.springframework.web.bind.MethodArgumentNotValidException;<br>import org.springframework.web.bind.annotation.ExceptionHandler;<br>import org.springframework.web.bind.annotation.RestControllerAdvice;<br><br>import java.time.Instant;<br>import java.util.List;<br><br>@Slf4j<br>@RestControllerAdvice<br>public class GlobalExceptionHandler {<br><br>    @ExceptionHandler(AiValidationException.class)<br>    public ResponseEntity&lt;ValidationErrorResponse&gt; handleAiValidation(<br>            AiValidationException ex, HttpServletRequest request) {<br><br>        log.warn(&quot;AI validation failed for [{}]&quot;, request.getRequestURI());<br><br>        List&lt;ValidationErrorResponse.FieldError&gt; fieldErrors =<br>                ex.getValidationResponse().fieldErrors().entrySet().stream()<br>                        .map(e -&gt; new ValidationErrorResponse.FieldError(e.getKey(), e.getValue()))<br>                        .toList();<br><br>        return ResponseEntity.unprocessableEntity()<br>                .body(new ValidationErrorResponse(<br>                        Instant.now(), HttpStatus.UNPROCESSABLE_ENTITY.value(),<br>                        &quot;Semantic validation failed&quot;, request.getRequestURI(), fieldErrors<br>                ));<br>    }<br><br>    @ExceptionHandler(MethodArgumentNotValidException.class)<br>    public ResponseEntity&lt;ValidationErrorResponse&gt; handleBeanValidation(<br>            MethodArgumentNotValidException ex, HttpServletRequest request) {<br><br>        List&lt;ValidationErrorResponse.FieldError&gt; fieldErrors =<br>                ex.getBindingResult().getFieldErrors().stream()<br>                        .map(e -&gt; new ValidationErrorResponse.FieldError(<br>                                e.getField(), e.getDefaultMessage()))<br>                        .toList();<br><br>        return ResponseEntity.badRequest()<br>                .body(new ValidationErrorResponse(<br>                        Instant.now(), HttpStatus.BAD_REQUEST.value(),<br>                        &quot;Validation failed&quot;, request.getRequestURI(), fieldErrors<br>                ));<br>    }<br><br>    @ExceptionHandler(Exception.class)<br>    public ResponseEntity&lt;ValidationErrorResponse&gt; handleUnexpected(<br>            Exception ex, HttpServletRequest request) {<br><br>        log.error(&quot;Unexpected error [{}]: {}&quot;, request.getRequestURI(), ex.getMessage(), ex);<br><br>        return ResponseEntity.internalServerError()<br>                .body(new ValidationErrorResponse(<br>                        Instant.now(), HttpStatus.INTERNAL_SERVER_ERROR.value(),<br>                        &quot;An unexpected error occurred&quot;, request.getRequestURI(), List.of()<br>                ));<br>    }<br>}</pre><p>We use 422 Unprocessable Entity for AI validation failures rather than 400 Bad Request. The distinction: 400 means the request is malformed — bad JSON, missing headers. 422 means the request arrived correctly but the content is semantically unacceptable. AI validation is semantic. Both handlers return the same ValidationErrorResponse structure so the client writes one error handler for all validation types.</p><h4>Step 9: Service</h4><pre>package blog.bouguern.smartvalidation.service;<br><br>import blog.bouguern.smartvalidation.dto.JobApplicationDTO;<br>import blog.bouguern.smartvalidation.exception.AiValidationException;<br>import blog.bouguern.smartvalidation.validation.AiValidationResponse;<br>import blog.bouguern.smartvalidation.validation.AiValidator;<br>import lombok.RequiredArgsConstructor;<br>import lombok.extern.slf4j.Slf4j;<br>import org.springframework.stereotype.Service;<br><br>import java.util.UUID;<br><br>@Slf4j<br>@Service<br>@RequiredArgsConstructor<br>public class JobApplicationService {<br><br>    private final AiValidator aiValidator;<br><br>    public String processApplication(JobApplicationDTO dto) {<br>        log.info(&quot;Processing application for: {}&quot;, dto.getFullName());<br><br>        AiValidationResponse response = aiValidator.validate(dto);<br><br>        if (!response.isValid()) {<br>            log.warn(&quot;AI validation failed for: {}&quot;, dto.getEmail());<br>            throw new AiValidationException(response);<br>        }<br><br>        log.info(&quot;Application from {} passed all validations.&quot;, dto.getEmail());<br>        return UUID.randomUUID().toString();<br>    }<br>}</pre><h4>Step 10: Controller</h4><pre>package blog.bouguern.smartvalidation.controller;<br><br>import blog.bouguern.smartvalidation.dto.JobApplicationDTO;<br>import blog.bouguern.smartvalidation.service.JobApplicationService;<br>import jakarta.servlet.http.HttpServletRequest;<br>import jakarta.validation.Valid;<br>import lombok.RequiredArgsConstructor;<br>import org.springframework.http.ResponseEntity;<br>import org.springframework.web.bind.annotation.*;<br><br>import java.net.URI;<br>import java.util.Map;<br><br>@RestController<br>@RequestMapping(&quot;/api/v1/applications&quot;)<br>@RequiredArgsConstructor<br>public class JobApplicationController {<br><br>    private final JobApplicationService jobApplicationService;<br><br>    @PostMapping<br>    public ResponseEntity&lt;Map&lt;String, String&gt;&gt; submitApplication(<br>            @Valid @RequestBody JobApplicationDTO dto,<br>            HttpServletRequest request) {<br><br>        String applicationId = jobApplicationService.processApplication(dto);<br>        URI location = URI.create(request.getRequestURI() + &quot;/&quot; + applicationId);<br><br>        return ResponseEntity.created(location)<br>                .body(Map.of(<br>                        &quot;status&quot;,        &quot;success&quot;,<br>                        &quot;applicationId&quot;, applicationId,<br>                        &quot;message&quot;,       &quot;Your application has been received&quot;<br>                ));<br>    }<br>}</pre><p>The controller handles only the happy path. @Valid triggers Bean Validation before the method body runs. If Bean Validation fails, Spring throws MethodArgumentNotValidException automatically and this method is never reached. If AI validation fails, AiValidationException propagates to GlobalExceptionHandler. This is the correct Spring MVC pattern — controllers handle only the happy path.</p><h3>Running and Testing</h3><h4>Postman Test Cases</h4><pre>Base URL: http://localhost:8981/api/v1/applications<br>Method: POST<br>Header: Content-Type: application/json</pre><h4>Here are 9 bodies to test:</h4><p><strong>Case 1 — Valid application → </strong>201 Created</p><pre>{<br>  &quot;fullName&quot;: &quot;Mohamed Bouguern&quot;,<br>  &quot;jobTitle&quot;: &quot;Senior Software Engineer&quot;,<br>  &quot;email&quot;: &quot;mohamed.bg@example.com&quot;,<br>  &quot;professionalSummary&quot;: &quot;Experienced Java developer with 5 years building Spring Boot microservices and REST APIs.&quot;,<br>  &quot;linkedInUrl&quot;: &quot;https://www.linkedin.com/in/mohamed-bouguern/&quot;<br>}</pre><p><strong>Case 2 — Gibberish values → </strong>422 Unprocessable Entity</p><pre>{<br>  &quot;fullName&quot;: &quot;aaaaabbbb1234$$&quot;,<br>  &quot;jobTitle&quot;: &quot;I like eating pizza&quot;,<br>  &quot;email&quot;: &quot;test@example.com&quot;,<br>  &quot;professionalSummary&quot;: &quot;Lorem ipsum dolor sit amet consectetur adipiscing elit sed do eiusmod tempor incididunt ut.&quot;<br>}</pre><p><strong>Case 3 — Missing required fields → </strong>400 Bad Request</p><pre>{}</pre><p><strong>Case 4 — Invalid email format → </strong>400 Bad Request</p><pre>{<br>  &quot;fullName&quot;: &quot;Mohamed Bouguern&quot;,<br>  &quot;jobTitle&quot;: &quot;Senior Software Engineer&quot;,<br>  &quot;email&quot;: &quot;not-an-email&quot;,<br>  &quot;professionalSummary&quot;: &quot;Experienced Java developer with 5 years building Spring Boot microservices and REST APIs.&quot;<br>}</pre><p><strong>Case 5 — Summary too short → </strong>400 Bad Request</p><pre>{<br>  &quot;fullName&quot;: &quot;Mohamed Bouguern&quot;,<br>  &quot;jobTitle&quot;: &quot;Senior Software Engineer&quot;,<br>  &quot;email&quot;: &quot;mohamed@example.com&quot;,<br>  &quot;professionalSummary&quot;: &quot;Too short.&quot;<br>}</pre><p><strong>Case 6 — Lorem ipsum summary → </strong>422 Unprocessable Entity</p><pre>{<br>  &quot;fullName&quot;: &quot;Mohamed Bouguern&quot;,<br>  &quot;jobTitle&quot;: &quot;Senior Software Engineer&quot;,<br>  &quot;email&quot;: &quot;mohamed@example.com&quot;,<br>  &quot;professionalSummary&quot;: &quot;Lorem ipsum dolor sit amet consectetur adipiscing elit sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.&quot;<br>}</pre><p><strong>Case 7 — Valid without optional LinkedIn → </strong>201 Created</p><pre>{<br>  &quot;fullName&quot;: &quot;Mohamed Bouguern&quot;,<br>  &quot;jobTitle&quot;: &quot;Full-Stack Java Developer&quot;,<br>  &quot;email&quot;: &quot;mohamed@example.com&quot;,<br>  &quot;professionalSummary&quot;: &quot;Full-Stack Java and Angular developer with 5 years of experience in Spring Boot microservices and AI integration.&quot;<br>}</pre><p><strong>Case 8 — Invalid LinkedIn URL → </strong>422 Unprocessable Entity</p><pre>{<br>  &quot;fullName&quot;: &quot;Mohamed Bouguern&quot;,<br>  &quot;jobTitle&quot;: &quot;Senior Software Engineer&quot;,<br>  &quot;email&quot;: &quot;mohamed@example.com&quot;,<br>  &quot;professionalSummary&quot;: &quot;Experienced Java developer with 5 years building Spring Boot microservices and REST APIs in enterprise environments.&quot;,<br>  &quot;linkedInUrl&quot;: &quot;https://randomwebsite.com/notlinkedin&quot;<br>}</pre><p><strong>Case 9 — All fields gibberish → </strong>422 Unprocessable Entity</p><pre>{<br>  &quot;fullName&quot;: &quot;xyz123!!!&quot;,<br>  &quot;jobTitle&quot;: &quot;asdfghjkl&quot;,<br>  &quot;email&quot;: &quot;test@test.com&quot;,<br>  &quot;professionalSummary&quot;: &quot;aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa&quot;,<br>  &quot;linkedInUrl&quot;: &quot;http://randomsite.com&quot;<br>}</pre><h3>Why This Approach Scales to Any DTO</h3><p>The validator requires zero changes when you add a new DTO. Simply create the class and pass it to aiValidator.validate().</p><p>For a product catalog API:</p><pre>@Data<br>public class CreateProductDTO {<br><br>    @NotBlank(message = &quot;Product name is required&quot;)<br>    private String name;<br><br>    private String description;<br><br>    private String category;<br>}</pre><p>No annotations. No new validator class. No configuration. The AI infers validation rules from field names and values. Pass it to aiValidator.validate(dto) and it works.</p><h3>Production Considerations</h3><p><strong>Latency.</strong> One AI call adds 400–600ms. Acceptable for form submissions. Not acceptable for search endpoints. Choose where you apply this deliberately.</p><p><strong>Cost.</strong> Groq’s free tier allows 14,400 requests per day on Llama 3.3 70B. For higher volume, model cost against your actual traffic.</p><p><strong>Fallback.</strong> When fallback-on-ai-failure: true, the request passes if Groq is unavailable. Set to false in strict environments where data quality is critical.</p><p><strong>Data privacy.</strong> In this implementation, DTO field values are sent to an external API. For sensitive data — personal identification numbers, financial data — either anonymize field values before sending, or use a locally-hosted model such as Ollama.</p><h3>Conclusion</h3><p>Classical Bean Validation answers: “Is this value the right format?” AI Semantic Validation answers: “Does this value make sense?”</p><p>Both questions matter. Neither replaces the other.</p><p>What makes this implementation different from typical AI validation tutorials: one API call for the entire DTO regardless of how many fields it has. The AI sees all fields together and detects cross-field inconsistencies. The architecture is generic — adding validation to a new DTO requires zero infrastructure changes.</p><p>The complete source code is available on GitHub: <a href="https://github.com/bouguern/smart-validation.git">Repository</a></p><p><em>Follow me on Medium for more articles. Connect with me on LinkedIn: </em><a href="https://www.linkedin.com/in/mohamed-bouguern/"><em>LinkedIn Profile</em></a></p><p>Thank you.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=25b504172396" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Effective State Management and Reactive Programming with Observables in Angular Using NgRx]]></title>
            <link>https://medium.com/@bouguern.mohamed/effective-state-management-and-reactive-programming-with-observables-in-angular-using-ngrx-08880461e089?source=rss-9126d0af0ba2------2</link>
            <guid isPermaLink="false">https://medium.com/p/08880461e089</guid>
            <category><![CDATA[ngrx]]></category>
            <category><![CDATA[ngrx-store]]></category>
            <category><![CDATA[angular]]></category>
            <category><![CDATA[rxjs-observables]]></category>
            <category><![CDATA[reactive-programming]]></category>
            <dc:creator><![CDATA[Mohamed Bouguern]]></dc:creator>
            <pubDate>Mon, 08 Jul 2024 12:39:19 GMT</pubDate>
            <atom:updated>2024-07-08T12:39:19.737Z</atom:updated>
            <content:encoded><![CDATA[<h4><strong>1. Introduction</strong></h4><p>In modern web development, managing state and ensuring seamless data flow within applications can be a daunting task. Angular, a popular framework for building dynamic web applications, offers robust tools to handle these challenges. One of the most powerful solutions for state management in Angular is NgRx, a reactive state management library that leverages the power of observables and reactive programming. This blog explores effective state management and reactive programming with observables in Angular using NgRx, providing a comprehensive guide to harnessing these tools for building efficient, maintainable applications.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/884/1*1c-Vb5Z6OWtGRPFlKqL0Zg.png" /></figure><h4><strong>2. What is NgRx?</strong></h4><p>NgRx is a suite of reactive libraries for Angular, inspired by the Redux pattern commonly used in React applications. It provides a powerful framework for managing the state of an Angular application in a predictable and consistent manner. NgRx consists of several core libraries, including @ngrx/store, @ngrx/effects, @ngrx/entity, and @ngrx/store-devtools, each offering distinct functionalities to streamline state management and side effects handling. By adopting a unidirectional data flow, NgRx ensures that the application state is always in sync, making it easier to debug and reason about.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LmOkWDDQy19QATh6Nro_Fw.png" /></figure><ul><li>@ngrx/store is the core library in the NgRx suite and is responsible for managing the state of an Angular application. It implements the Redux pattern, providing a centralized store to hold the application state.</li><li>@ngrx/effects is a library designed to handle side effects in an Angular application. Side effects are operations like HTTP requests, logging, and other asynchronous tasks that affect the application state.</li><li>@ngrx/entity simplifies the process of managing collections of entities in your state. It provides utility functions to manipulate collections efficiently.</li><li>@ngrx/store-devtools is a set of developer tools that help in debugging and monitoring the state changes in an NgRx application.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/618/1*jhj2sxI8tDnRnE0daVARQg.png" /></figure><h4><strong>3. What is Reactive Programming in Angular?</strong></h4><p>Reactive programming is a paradigm that focuses on asynchronous data streams and the propagation of changes. In Angular, reactive programming is primarily facilitated through RxJS (Reactive Extensions for JavaScript), a library that allows developers to work with asynchronous events and data streams in a declarative manner. Reactive programming in Angular emphasizes the use of observables, a core concept in RxJS, to handle asynchronous operations like HTTP requests, user inputs, and more. This approach enables developers to build responsive and resilient applications by efficiently managing asynchronous data flows and side effects.</p><h4><strong>4. </strong>What is <strong>Observables in Angular?</strong></h4><p>Observables are a key feature of RxJS and play a crucial role in Angular’s reactive programming model. An observable is a data stream that can emit multiple values over time, which can be observed and reacted to. Observables provide a powerful way to handle asynchronous events, such as data fetching, user interactions, and real-time updates, by allowing developers to compose and manage complex event sequences declaratively. In Angular, observables are extensively used in services, components, and various Angular modules to manage asynchronous data flows and state changes seamlessly.</p><h4><strong>5. The benefits of NgRx</strong></h4><ul><li><strong>Predictable State Management</strong>: NgRx follows the Redux pattern, which enforces a unidirectional data flow and a single source of truth for the application state. This predictability simplifies debugging and makes the state changes more transparent and easier to track.</li><li><strong>Immutability</strong>: NgRx promotes immutability, ensuring that the state is never mutated directly. Instead, new state objects are created, which helps in maintaining a clear and consistent application state, reducing the chances of unexpected side effects.</li><li><strong>Scalability</strong>: As applications grow in complexity, managing state and side effects becomes increasingly challenging. NgRx provides a scalable architecture that can handle complex state interactions and side effects through its modular design, making it suitable for large-scale applications.</li><li><strong>Enhanced Debugging</strong>: With tools like @ngrx/store-devtools, developers can inspect and replay state changes, making it easier to identify and resolve issues. Time-travel debugging allows developers to step through state changes, providing a clear understanding of how actions affect the state.</li></ul><p>- Scalable and Suitable for complex applications with a need for reactive data (e.g., real-time chat App, shopping cart, etc…).</p><h4><strong>6. Prerequisites</strong></h4><ul><li>Before diving into NgRx, ensure you have a basic understanding of Reactive Programming, Observables, and NgRx concepts.</li><li>Ensure you have Angular CLI installed:</li></ul><pre>npm install -g @angular/cli</pre><h4><strong>7. Create a new Angular project</strong></h4><pre>ng new angular-state-management-ngrx<br>cd angular-state-management-ngrx</pre><h4><strong>8. Install NgRx and Related Dependencies</strong></h4><p><a href="https://ngrx.io/">NgRx</a> can be installed using NPM as follows:</p><pre>npm install @ngrx/store@15 @ngrx/effects@15 @ngrx/entity@15 @ngrx/st<br>ore-devtools@15 --save</pre><h4><strong>9. Now, Let’s build the App</strong></h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/270/1*aRR2lb268YU31PBSbiRWrg.png" /><figcaption>Structure of the App</figcaption></figure><p><strong>9.1) product.actions.ts: </strong>In NgRx, actions are payloads of information that send data from your application to your store. They are typically dispatched in response to user interactions or events. The createAction function from @ngrx/store helps create these actions easily:</p><pre>import { createAction, props } from &#39;@ngrx/store&#39;;<br>import { Product } from &#39;src/app/models/Product&#39;;<br><br>// Load Products<br>export const loadProducts = createAction(&#39;[Product] Load Products&#39;);<br>export const loadProductsSuccess = createAction(&#39;[Product] Load Products Success&#39;, props&lt;{ products: Product[] }&gt;());<br>export const loadProductsFailure = createAction(&#39;[Product] Load Products Failure&#39;, props&lt;{ error: any }&gt;());<br><br>// Add Product<br>export const addProduct = createAction(&#39;[Product] Add Product&#39;, props&lt;{ product: Product }&gt;());<br>export const addProductSuccess = createAction(&#39;[Product] Add Product Success&#39;, props&lt;{ products: Product[] }&gt;());<br>export const addProductFailure = createAction(&#39;[Product] Add Product Failure&#39;, props&lt;{ error: any }&gt;());<br><br>// Update Product<br>export const updateProduct = createAction(&#39;[Product] Update Product&#39;, props&lt;{ product: Product }&gt;());<br>export const updateProductSuccess = createAction(&#39;[Product] Update Product Success&#39;, props&lt;{ products: Product[] }&gt;());<br>export const updateProductFailure = createAction(&#39;[Product] Update Product Failure&#39;, props&lt;{ error: any }&gt;());<br><br>// Delete Product<br>export const deleteProduct = createAction(&#39;[Product] Delete Product&#39;, props&lt;{ productId: number }&gt;());<br>export const deleteProductSuccess = createAction(&#39;[Product] Delete Product Success&#39;, props&lt;{ products: Product[] }&gt;());<br>export const deleteProductFailure = createAction(&#39;[Product] Delete Product Failure&#39;, props&lt;{ error: any }&gt;());</pre><ul><li><strong>createAction</strong>: A function to define actions.</li><li><strong>props</strong>: A utility to define the payload (properties) of an action.</li><li><strong>Product</strong>: An interface representing the product model.</li><li><strong>loadProducts</strong>: This action is dispatched to initiate the loading of products. It doesn’t carry any payload.</li><li><strong>loadProductsSuccess</strong>: This action is dispatched when the products are successfully loaded. It carries a payload of the loaded products.</li><li><strong>loadProductsFailure</strong>: This action is dispatched if there is an error loading the products. It carries a payload of the error.</li><li><strong>addProduct</strong>: This action is dispatched to add a new product. It carries a payload of the product to be added.</li><li><strong>addProductSuccess</strong>: This action is dispatched when a product is successfully added. It carries a payload of the updated products.</li><li><strong>addProductFailure</strong>: This action is dispatched if there is an error adding the product. It carries a payload of the error.</li><li><strong>updateProduct</strong>: This action is dispatched to update an existing product. It carries a payload of the product to be updated.</li><li><strong>updateProductSuccess</strong>: This action is dispatched when a product is successfully updated. It carries a payload of the updated products.</li><li><strong>updateProductFailure</strong>: This action is dispatched if there is an error updating the product. It carries a payload of the error.</li><li><strong>deleteProduct</strong>: This action is dispatched to delete a product. It carries a payload of the product ID to be deleted.</li><li><strong>deleteProductSuccess</strong>: This action is dispatched when a product is successfully deleted. It carries a payload of the updated products.</li><li><strong>deleteProductFailure</strong>: This action is dispatched if there is an error deleting the product. It carries a payload of the error.</li></ul><p><strong>9.2) </strong><strong>product.state.ts:</strong> This file defines the state structure for managing products using NgRx&#39;s Entity Adapter, which simplifies handling collections of entities.</p><pre>import { EntityState, createEntityAdapter } from &quot;@ngrx/entity&quot;;<br>import { Product } from &quot;src/app/models/Product&quot;;<br><br>export interface ProductState extends EntityState&lt;Product&gt; {<br>  loading: boolean;<br>  error: string | null; <br>}<br><br>export const productAdapter = createEntityAdapter&lt;Product&gt;();<br><br>export const initialState: ProductState = productAdapter.getInitialState({<br>  //products: [],<br>  //selectedProductId: null,<br>  loading: false,<br>  error: null<br>});</pre><ul><li><strong>EntityState</strong>: An interface that extends the NgRx store’s state to manage collections of entities.</li><li><strong>createEntityAdapter</strong>: A function that creates an entity adapter, providing utility methods for managing entity collections.</li><li><strong>Product</strong>: An interface representing the product model.</li><li><strong>ProductState</strong>: Extends EntityState to include additional state properties specific to product management.</li><li><strong>loading</strong>: A boolean flag indicating whether the products are currently being loaded.</li><li><strong>error</strong>: A string or null, representing any error that occurs during product operations.</li><li><strong>productAdapter</strong>: An entity adapter created for the Product model. This adapter provides utility methods to manage collections of products, such as adding, updating, and removing entities.</li><li><strong>getInitialState</strong>: A method provided by the entity adapter to get the initial state for the entity collection. This method can take an object to define additional properties for the state.</li><li>The initial state is configured using the getInitialState method of the entity adapter. This method initializes the state with the following properties:</li><li><strong>loading</strong>: Set to false, indicating that the products are not currently being loaded.</li><li><strong>error</strong>: Set to null, indicating that there are no errors initially.</li></ul><p><strong>9.3) </strong><strong>product.selectors.ts:</strong> This file defines various selectors to access different slices of the product state within the NgRx store:</p><pre>import { createFeatureSelector, createSelector } from &#39;@ngrx/store&#39;;<br>import { ProductState } from &#39;./product.state&#39;;<br><br>import { selectAll } from &#39;./product.reducer&#39;;<br><br>// Select the feature state <br>export const selectProductState = createFeatureSelector&lt;ProductState&gt;(&#39;products&#39;);<br><br>// Selectors for product entities<br>export const selectAllProducts = createSelector(<br>  selectProductState,<br>  selectAll<br>);<br><br>export const selectProductEntities = createSelector(<br>  selectProductState,<br>  selectAll,<br>  (state, products) =&gt; products<br>);<br><br>export const selectProductIds = createSelector(<br>  selectProductState,<br>  selectAll,<br>  (state, products) =&gt; products<br>);<br><br>export const selectProductById = (productId: number) =&gt; createSelector(<br>  selectProductEntities,<br>  entities =&gt; entities[productId]<br>);<br><br>// Selectors for loading and error state<br>export const selectLoading = createSelector(<br>  selectProductState,<br>  state =&gt; state.loading<br>);<br><br>export const selectError = createSelector(<br>  selectProductState,<br>  state =&gt; state.error<br>);</pre><ul><li><strong>createFeatureSelector</strong>: A function to select a feature state from the store.</li><li><strong>createSelector</strong>: A function to create selectors for slices of the state.</li><li><strong>ProductState</strong>: The interface representing the state structure for products.</li><li><strong>selectAll</strong>: A selector provided by the entity adapter to select all products.</li><li><strong>selectProductState</strong>: This selector fetches the entire product state slice from the store, using the key products.</li><li><strong>selectAllProducts</strong>: This selector combines the selectProductState selector and the selectAll selector to get all product entities from the product state.</li><li><strong>selectProductEntities</strong>: This selector gets all product entities from the state. It’s somewhat redundant with selectAllProducts but might be used for specific use cases.</li><li><strong>selectProductIds</strong>: Similar to selectProductEntities, it gets all product entities but is intended to focus on extracting product IDs if needed.</li><li><strong>selectProductById</strong>: This selector gets a single product entity by its ID. It takes productId as an argument and returns a selector that finds the product in the entities collection.</li><li><strong>selectLoading</strong>: This selector gets the loading state from the product state, indicating whether the products are currently being loaded.</li><li><strong>selectError</strong>: This selector gets the error state from the product state, providing any error message that occurred during product operations.</li></ul><p><strong>9.4) </strong><strong>product.reducer.ts: </strong>This file defines the reducer for handling product-related actions in the NgRx store:</p><pre>import { createReducer, on } from &#39;@ngrx/store&#39;;<br>import { ProductState, initialState, productAdapter } from &#39;./product.state&#39;;<br>import * as ProductActions from &#39;./product.actions&#39;;<br><br>export const productReducer = createReducer(<br>  initialState,<br><br>  on(ProductActions.loadProducts, state =&gt; ({<br>    ...state,<br>    loading: true,<br>    error: null<br>  })),<br>  on(ProductActions.loadProductsSuccess, (state, { products }) =&gt;<br>    productAdapter.setAll(products, { ...state, loading: false })<br>  ),<br>  on(ProductActions.loadProductsFailure, (state, { error }) =&gt; ({<br>    ...state,<br>    loading: false,<br>    error: error.message || &#39;Load products failed&#39;<br>  })),<br><br>  on(ProductActions.addProductSuccess, (state, { products }) =&gt;<br>    productAdapter.setAll(products, { ...state })<br>  ),<br>  on(ProductActions.addProductFailure, (state, { error }) =&gt; ({<br>    ...state,<br>    error: error.message || &#39;Add product failed&#39;<br>  })),<br><br>  on(ProductActions.updateProductSuccess, (state, { products }) =&gt;<br>    productAdapter.setAll(products, { ...state })<br>  ),<br>  on(ProductActions.updateProductFailure, (state, { error }) =&gt; ({<br>    ...state,<br>    error: error.message || &#39;Update product failed&#39;<br>  })),<br><br>  on(ProductActions.deleteProductSuccess, (state, { products }) =&gt;<br>    productAdapter.setAll(products, { ...state })<br>  ),<br>  on(ProductActions.deleteProductFailure, (state, { error }) =&gt; ({<br>    ...state,<br>    error: error.message || &#39;Delete product failed&#39;<br>  }))<br>);<br><br>// Export entity selectors from the adapter<br>export const {<br>  selectAll,<br>  selectEntities,<br>  selectIds,<br>} = productAdapter.getSelectors();<br><br>export const selectLoading = (state: ProductState) =&gt; state.loading;<br>export const selectError = (state: ProductState) =&gt; state.error;</pre><ul><li><strong>createReducer</strong>: A function to define a reducer function in a concise way.</li><li><strong>on</strong>: A function to handle specific actions within the reducer.</li><li><strong>ProductState</strong>: The interface representing the state structure for products.</li><li><strong>initialState</strong>: The initial state of the product slice.</li><li><strong>productAdapter</strong>: The entity adapter for products, providing utility methods for managing product collections.</li><li><strong>ProductActions</strong>: The set of actions related to products.</li><li><strong>productReducer</strong>: The reducer function for the product state. It handles various actions defined in ProductActions and updates the state accordingly.</li><li><strong>loadProducts</strong>: When the loadProducts action is dispatched, the state is updated to set loading to true and error to null.</li><li><strong>loadProductsSuccess</strong>: When the loadProductsSuccess action is dispatched, the state is updated using the setAll method of the entity adapter to set the products and set loading to false.</li><li><strong>loadProductsFailure</strong>: When the loadProductsFailure action is dispatched, the state is updated to set loading to false and error to the provided error message.</li><li><strong>addProductSuccess</strong>: When the addProductSuccess action is dispatched, the state is updated to set the new list of products using setAll.</li><li><strong>addProductFailure</strong>: When the addProductFailure action is dispatched, the state is updated to set the error to the provided error message.</li><li><strong>updateProductSuccess</strong>: When the updateProductSuccess action is dispatched, the state is updated to set the new list of products using setAll.</li><li><strong>updateProductFailure</strong>: When the updateProductFailure action is dispatched, the state is updated to set the error to the provided error message.</li><li><strong>deleteProductSuccess</strong>: When the deleteProductSuccess action is dispatched, the state is updated to set the new list of products using setAll.</li><li><strong>deleteProductFailure</strong>: When the deleteProductFailure action is dispatched, the state is updated to set the error to the provided error message.</li><li><strong>selectAll</strong>: A selector to get all products.</li><li><strong>selectEntities</strong>: A selector to get all product entities as a dictionary.</li><li><strong>selectIds</strong>: A selector to get all product IDs.</li><li><strong>selectLoading</strong>: A selector to get the loading state.</li><li><strong>selectError</strong>: A selector to get the error state.</li></ul><p><strong>9.5) </strong><strong>product.effects.ts: </strong>This file defines the effects that handle side effects for product-related actions in the NgRx store:</p><pre>import { Injectable } from &#39;@angular/core&#39;;<br>import { Actions, createEffect, ofType } from &#39;@ngrx/effects&#39;;<br>import { catchError, map, mergeMap } from &#39;rxjs/operators&#39;;<br>import { of } from &#39;rxjs&#39;;<br>import * as ProductActions from &#39;./product.actions&#39;;<br>import { ProductService } from &#39;../../services/product.service&#39;;<br><br>@Injectable() <br>export class ProductEffects {<br>  constructor(private actions$: Actions, private productService: ProductService) {}<br><br>  loadProducts$ = createEffect(() =&gt; this.actions$.pipe(<br>    ofType(ProductActions.loadProducts),<br>    mergeMap(() =&gt; this.productService.getAllProducts().pipe(<br>      map(products =&gt; ProductActions.loadProductsSuccess({ products })),<br>      catchError(error =&gt; of(ProductActions.loadProductsFailure({ error })))<br>    ))<br>  ));<br><br>  addProduct$ = createEffect(() =&gt; this.actions$.pipe(<br>    ofType(ProductActions.addProduct),<br>    mergeMap(action =&gt; this.productService.addProduct(action.product).pipe(<br>      map(products =&gt; ProductActions.addProductSuccess({ products })),<br>      catchError(error =&gt; of(ProductActions.addProductFailure({ error })))<br>    ))<br>  ));<br><br>  updateProduct$ = createEffect(() =&gt; this.actions$.pipe(<br>    ofType(ProductActions.updateProduct),<br>    mergeMap(action =&gt; this.productService.updateProduct(action.product).pipe(<br>      map(products =&gt; ProductActions.updateProductSuccess({ products })),<br>      catchError(error =&gt; of(ProductActions.updateProductFailure({ error })))<br>    ))<br>  ));<br><br>  deleteProduct$ = createEffect(() =&gt; this.actions$.pipe(<br>    ofType(ProductActions.deleteProduct),<br>    mergeMap(action =&gt; this.productService.deleteProduct(action.productId).pipe(<br>      map(products =&gt; ProductActions.deleteProductSuccess({ products })),<br>      catchError(error =&gt; of(ProductActions.deleteProductFailure({ error })))<br>    ))<br>  ));<br>}</pre><ul><li><strong>Injectable</strong>: A decorator that marks a class as available to be provided and injected as a dependency.</li><li><strong>Actions</strong>: A stream of dispatched actions.</li><li><strong>createEffect</strong>: A function to create an effect.</li><li><strong>ofType</strong>: A filter to select specific action types from the actions stream.</li><li><strong>catchError, map, mergeMap</strong>: RxJS operators used to handle side effects and transformations.</li><li><strong>of</strong>: A function to create an observable from static values.</li><li><strong>ProductActions</strong>: The set of actions related to products.</li><li><strong>ProductService</strong>: The service to handle product-related operations.</li><li><strong>ProductEffects</strong>: The class that defines the effects for product-related actions.</li><li><strong>actions$</strong>: A stream of dispatched actions, injected by NgRx.</li><li><strong>productService</strong>: The service to handle product-related operations, injected as a dependency.</li><li><strong>loadProducts$</strong>: An effect that handles the loadProducts action.</li><li><strong>ofType(ProductActions.loadProducts)</strong>: Filters for the loadProducts action.</li><li><strong>mergeMap</strong>: Maps the action to an observable, in this case, the observable returned by productService.getAllProducts().</li><li><strong>map(products =&gt; ProductActions.loadProductsSuccess({ products }))</strong>: Maps the response to a loadProductsSuccess action.</li><li><strong>catchError(error =&gt; of(ProductActions.loadProductsFailure({ error })))</strong>: Catches any errors and maps them to a loadProductsFailure action.</li><li><strong>addProduct$</strong>: An effect that handles the addProduct action.</li><li><strong>ofType(ProductActions.addProduct)</strong>: Filters for the addProduct action.</li><li><strong>mergeMap(action =&gt; this.productService.addProduct(action.product).pipe(…)</strong>: Maps the action to the observable returned by productService.addProduct.</li><li><strong>map(products =&gt; ProductActions.addProductSuccess({ products }))</strong>: Maps the response to an addProductSuccess action.</li><li><strong>catchError(error =&gt; of(ProductActions.addProductFailure({ error })))</strong>: Catches any errors and maps them to an addProductFailure action.</li><li><strong>updateProduct$</strong>: An effect that handles the updateProduct action.</li><li><strong>ofType(ProductActions.updateProduct)</strong>: Filters for the updateProduct action.</li><li><strong>mergeMap(action =&gt; this.productService.updateProduct(action.product).pipe(…)</strong>: Maps the action to the observable returned by productService.updateProduct.</li><li><strong>map(products =&gt; ProductActions.updateProductSuccess({ products }))</strong>: Maps the response to an updateProductSuccess action.</li><li><strong>catchError(error =&gt; of(ProductActions.updateProductFailure({ error })))</strong>: Catches any errors and maps them to an updateProductFailure action.</li><li><strong>deleteProduct$</strong>: An effect that handles the deleteProduct action.</li><li><strong>ofType(ProductActions.deleteProduct)</strong>: Filters for the deleteProduct action.</li><li><strong>mergeMap(action =&gt; this.productService.deleteProduct(action.productId).pipe(…)</strong>: Maps the action to the observable returned by productService.deleteProduct.</li><li><strong>map(products =&gt; ProductActions.deleteProductSuccess({ products }))</strong>: Maps the response to a deleteProductSuccess action.</li><li><strong>catchError(error =&gt; of(ProductActions.deleteProductFailure({ error })))</strong>: Catches any errors and maps them to a deleteProductFailure action.</li></ul><p><strong>9.6) The </strong><strong>ProductService:</strong> Designed to manage a list of products. It uses the RxJS library to work with asynchronous data streams:</p><pre>import { Injectable } from &#39;@angular/core&#39;;<br>import { Observable, of, throwError } from &#39;rxjs&#39;;<br>import { Product } from &#39;../models/Product&#39;;<br><br>@Injectable({<br>  providedIn: &#39;root&#39;<br>})<br>export class ProductService {<br><br>  private products: Product[] = [<br>    { id: 1, name: &#39;p 1&#39;, price: 95 },<br>    { id: 2, name: &#39;p 2&#39;, price: 745 },<br>    { id: 3, name: &#39;p 3&#39;, price: 58 },<br>    { id: 4, name: &#39;p 4&#39;, price: 9 },<br>  ];<br><br>  constructor() { }<br><br>  getAllProducts(): Observable&lt;Product[]&gt; {<br>    return of([...this.products]); // Return a copy of products array<br>  }<br><br>  addProduct(product: Product): Observable&lt;Product[]&gt; {<br>    this.products = [...this.products, product]; // Add new product to a new array<br>    return of([...this.products]);<br>  }<br><br>  updateProduct(product: Product): Observable&lt;Product[]&gt; {<br>    const index = this.products.findIndex(p =&gt; p.id === product.id);<br>    if (index !== -1) {<br>      this.products = [<br>        ...this.products.slice(0, index),<br>        product,<br>        ...this.products.slice(index + 1)<br>      ];<br>      return of([...this.products]);<br>    } else {<br>      return throwError(&#39;Product not found&#39;);<br>    }<br>  }<br><br>  deleteProduct(productId: number): Observable&lt;Product[]&gt; {<br>    this.products = this.products.filter(product =&gt; product.id !== productId);<br>    return of([...this.products]);<br>  }<br><br>}</pre><ul><li>Observable, of, throwError, catchError: RxJS utilities for handling asynchronous operations and errors.</li></ul><ol><li><strong>getAllProducts()</strong></li></ol><ul><li><strong>Description</strong>: Returns an observable of the entire product list.</li><li><strong>Implementation</strong>: Uses of([...this.products]) to emit a copy of the products array, ensuring immutability.</li></ul><p>2. <strong>addProduct(product: Product)</strong></p><ul><li><strong>Description</strong>: Adds a new product to the product list.</li><li><strong>Implementation</strong>: Creates a new array with the existing products and the new product, ensuring the original array is not mutated. It then emits the updated product list.</li></ul><p><strong>3. updateProduct(product: Product)</strong></p><ul><li><strong>Description</strong>: Updates an existing product in the product list.</li><li><strong>Implementation</strong>:</li></ul><p>=&gt; Finds the index of the product to be updated.</p><p>=&gt; If the product is found, creates a new array with the updated product replacing the old one, ensuring immutability.</p><p>=&gt; Emits the updated product list.</p><p>=&gt; If the product is not found, returns an observable error using throwError.</p><p>4. <strong>deleteProduct(productId: number)</strong></p><ul><li><strong>Description</strong>: Deletes a product from the product list by its ID.</li><li><strong>Implementation</strong>:</li></ul><p>=&gt; Filters the products array to exclude the product with the specified ID.</p><p>=&gt; Emits the updated product list, ensuring the original array is not mutated.</p><p>For a detailed view of the complete code and additional functionalities, please visit the <a href="https://github.com/bouguern/angular-state-management-ngrx.git"><strong>GitHub repository</strong></a>. The necessary code snippets and explanations have been provided here, but you can find the full implementation in the repository. Your feedback and contributions are welcome!</p><pre>https://github.com/bouguern/angular-state-management-ngrx.git</pre><h4><strong>Conclusion</strong></h4><p>In this overview of implementing state management in Angular using NgRx, we have covered the creation and use of actions, state, reducers, selectors, and effects. NgRx provides a powerful way to manage state in your applications, promoting a unidirectional data flow and enhancing the predictability of your application state. By using actions to trigger state changes, reducers to handle those changes, selectors to query state, and effects to manage side effects, you can build robust and scalable applications. This approach helps maintain a clean architecture, making your application easier to debug, test, and extend over time.</p><p><em>Thank YOU!</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=08880461e089" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Reading and Writing Excel Data in Spring Boot with Apache POI]]></title>
            <link>https://medium.com/@bouguern.mohamed/reading-and-writing-excel-data-in-spring-boot-with-apache-poi-139753529ebe?source=rss-9126d0af0ba2------2</link>
            <guid isPermaLink="false">https://medium.com/p/139753529ebe</guid>
            <category><![CDATA[apache-poi]]></category>
            <category><![CDATA[rest-api]]></category>
            <category><![CDATA[excel]]></category>
            <category><![CDATA[spring-boot]]></category>
            <category><![CDATA[read-excel-file]]></category>
            <dc:creator><![CDATA[Mohamed Bouguern]]></dc:creator>
            <pubDate>Tue, 02 Jul 2024 10:46:43 GMT</pubDate>
            <atom:updated>2024-07-02T10:46:43.715Z</atom:updated>
            <content:encoded><![CDATA[<ol><li><strong>Introduction</strong></li></ol><p>Handling Excel files is a common requirement for data import and export functionalities. Whether it’s for generating reports, processing large datasets, or exchanging information with other systems, Excel files provide a versatile and widely-used format. In this blog, we’ll explore how to read and write Excel data in a Spring Boot application using Apache POI, a powerful library for working with Microsoft Office documents.</p><p><strong>2. Why Use Apache POI?</strong></p><p>Apache POI is an open-source Java library that provides robust support for reading and writing Microsoft Office files, including Excel, Word, and PowerPoint. It offers a comprehensive API for manipulating Excel files, making it an excellent choice for developers who need to handle spreadsheet data in their applications.</p><p>To use Apache POI in your Spring Boot project, you need to include the following dependencies in your pom.xml file:</p><pre>&lt;dependency&gt;<br>    &lt;groupId&gt;org.apache.poi&lt;/groupId&gt;<br>    &lt;artifactId&gt;poi&lt;/artifactId&gt;<br>    &lt;version&gt;5.0.0&lt;/version&gt;<br>&lt;/dependency&gt;<br>&lt;dependency&gt;<br>    &lt;groupId&gt;org.apache.poi&lt;/groupId&gt;<br>    &lt;artifactId&gt;poi-ooxml&lt;/artifactId&gt;<br>    &lt;version&gt;5.0.0&lt;/version&gt;<br>&lt;/dependency&gt;</pre><ul><li><strong>poi Dependency:</strong> This dependency includes the core Apache POI library, which provides basic support for reading and writing Microsoft Office formats.</li><li><strong>poi-ooxml Dependency:</strong> This dependency adds support for the newer XML-based Excel file formats (.xlsx). It is necessary for working with modern Excel files created by Microsoft Office 2007 and later.</li></ul><p><strong>3. Let us start building the application!</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/405/1*6zV-KZbSmokDbaHMwlhD_A.png" /><figcaption>Project Structure</figcaption></figure><p>Explanation of the ReportServiceImpl Class:</p><p>The ReportServiceImpl class is a Spring Boot service that provides functionalities to read from and write to Excel files using Apache POI. Below is a detailed explanation of its key components:</p><h4>Logger</h4><p>A logger is used to log information, warnings, and errors.</p><pre>private static final Logger logger = LoggerFactory.getLogger(ReportServiceImpl.class);</pre><h3>Methods</h3><p><strong>saveEmployee()</strong></p><p>This method saves an Employee object to the database using the repository.</p><pre>@Override<br>public Employee saveEmployee(Employee employee) {<br>    return employeeRepository.save(employee);<br>}</pre><p><strong>generateExcel()</strong></p><p>This method generates an Excel file with employee information and writes it to the HTTP response.</p><ol><li><strong>Retrieve Employees:</strong> Fetches all employees from the repository.</li><li><strong>Create Workbook and Sheet:</strong> Initializes an HSSFWorkbook and creates a sheet named &quot;Employees Info&quot;.</li><li><strong>Create Header Row:</strong> Sets up the header row with column names.</li><li><strong>Date Cell Style:</strong> Defines a date cell style for formatting date cells.</li><li><strong>Populate Data Rows:</strong> Iterates through the employees and populates the rows with their data.</li><li><strong>Auto-size Columns:</strong> Adjusts the width of the columns to fit the content.</li><li><strong>Write to Response:</strong> Writes the workbook to the HTTP response output stream.</li></ol><pre>@Override<br>public void generateExcel(HttpServletResponse response) throws Exception {<br>    List&lt;Employee&gt; employees = employeeRepository.findAll();<br><br>    HSSFWorkbook workbook = new HSSFWorkbook();<br>    HSSFSheet sheet = workbook.createSheet(&quot;Employees Info&quot;);<br>    HSSFRow row = sheet.createRow(0);<br><br>    row.createCell(0).setCellValue(&quot;ID employee&quot;);<br>    row.createCell(1).setCellValue(&quot;First Name&quot;);<br>    row.createCell(2).setCellValue(&quot;Last Name&quot;);<br>    row.createCell(3).setCellValue(&quot;Started Date&quot;);<br><br>    HSSFCellStyle dateCellStyle = workbook.createCellStyle();<br>    HSSFDataFormat dateFormat = workbook.createDataFormat();<br>    dateCellStyle.setDataFormat(dateFormat.getFormat(&quot;dd-mm-yyyy&quot;));<br><br>    int dataRowIndex = 1;<br><br>    for (Employee employee : employees) {<br>        HSSFRow dataRow = sheet.createRow(dataRowIndex);<br>        dataRow.createCell(0).setCellValue(employee.getEmployeeId());<br>        dataRow.createCell(1).setCellValue(employee.getFirstName());<br>        dataRow.createCell(2).setCellValue(employee.getLastName());<br><br>        if(employee.getStartedDateInCompany() != null) {<br>            HSSFCell dateCell = dataRow.createCell(3);<br>            dateCell.setCellValue(Date.valueOf(employee.getStartedDateInCompany()));<br>            dateCell.setCellStyle(dateCellStyle);<br>        }<br><br>        dataRowIndex++;<br>    }<br><br>    for (int i = 0; i &lt; 4; i++) {<br>        sheet.autoSizeColumn(i);<br>    }<br><br>    ServletOutputStream ops = response.getOutputStream();<br>    workbook.write(ops);<br>    workbook.close();<br>    ops.close();<br>}</pre><p><strong>readExcelFile()</strong></p><p>This method reads data from an existing Excel file and converts it into a list of Course objects.</p><ol><li><strong>Initialize Workbook:</strong> Opens the Excel file specified by CSV_FILE_LOCATION.</li><li><strong>Iterate Sheets:</strong> Logs the number of sheets and iterates through them.</li><li><strong>Data Formatter:</strong> Uses DataFormatter to format cell values as strings.</li><li><strong>Parse Rows:</strong> Skips the header row and parses the remaining rows to create Course objects.</li><li><strong>Close Workbook:</strong> Ensures the workbook is closed after reading to free up resources.</li></ol><pre>@Override<br>public List&lt;Course&gt; readExcelFile() {<br>    List&lt;Course&gt; courses = new ArrayList&lt;&gt;();<br>    Workbook workbook = null;<br><br>    try {<br>        workbook = WorkbookFactory.create(new File(CSV_FILE_LOCATION));<br>        logger.info(&quot;Number of sheets: &quot; + workbook.getNumberOfSheets());<br><br>        workbook.forEach(sheet -&gt; {<br>            logger.info(&quot;Title of sheet =&gt; &quot; + sheet.getSheetName());<br><br>            DataFormatter dataFormatter = new DataFormatter();<br>            int index = 0;<br>            for (Row row : sheet) {<br>                if (index++ == 0) continue;<br>                Course course = new Course();<br><br>                if (row.getCell(0) != null &amp;&amp; row.getCell(0).getCellType() == CellType.NUMERIC) {<br>                    course.setId((int) row.getCell(0).getNumericCellValue());<br>                }<br><br>                if (row.getCell(1) != null) {<br>                    course.setName(dataFormatter.formatCellValue(row.getCell(1)));<br>                }<br><br>                Cell dateCell = row.getCell(2);<br>                if (DateUtil.isCellDateFormatted(dateCell)) {<br>                    LocalDate date = dateCell.getDateCellValue().toInstant().atZone(ZoneId.systemDefault()).toLocalDate();<br>                    course.setDate(date);<br>                }<br><br>                if (row.getCell(3) != null &amp;&amp; row.getCell(3).getCellType() == CellType.NUMERIC) {<br>                    course.setNumber((int) row.getCell(3).getNumericCellValue());<br>                }<br>                courses.add(course);<br>            }<br>        });<br>    } catch (EncryptedDocumentException | IOException e) {<br>        logger.error(e.getMessage(), e);<br>    } finally {<br>        try {<br>            if (workbook != null) workbook.close();<br>        } catch (IOException e) {<br>            logger.error(e.getMessage(), e);<br>        }<br>    }<br><br>    return courses;<br>}</pre><p>Here’s the complete code for the ReportServiceImpl class:</p><pre>package bouguern.tuto.demo.service;<br><br>import java.io.File;<br>import java.io.IOException;<br>import java.sql.Date;<br>import java.time.LocalDate;<br>import java.time.ZoneId;<br>import java.util.ArrayList;<br>import java.util.List;<br><br>import org.apache.poi.EncryptedDocumentException;<br>import org.apache.poi.hssf.usermodel.HSSFCell;<br>import org.apache.poi.hssf.usermodel.HSSFCellStyle;<br>import org.apache.poi.hssf.usermodel.HSSFDataFormat;<br>import org.apache.poi.hssf.usermodel.HSSFRow;<br>import org.apache.poi.hssf.usermodel.HSSFSheet;<br>import org.apache.poi.hssf.usermodel.HSSFWorkbook;<br>import org.apache.poi.ss.usermodel.Cell;<br>import org.apache.poi.ss.usermodel.CellType;<br>import org.apache.poi.ss.usermodel.DataFormatter;<br>import org.apache.poi.ss.usermodel.DateUtil;<br>import org.apache.poi.ss.usermodel.Row;<br>import org.apache.poi.ss.usermodel.Workbook;<br>import org.apache.poi.ss.usermodel.WorkbookFactory;<br>import org.slf4j.Logger;<br>import org.slf4j.LoggerFactory;<br>import org.springframework.stereotype.Service;<br><br>import bouguern.tuto.demo.entity.Course;<br>import bouguern.tuto.demo.entity.Employee;<br>import bouguern.tuto.demo.repository.EmployeeRepository;<br>import jakarta.servlet.ServletOutputStream;<br>import jakarta.servlet.http.HttpServletResponse;<br>import lombok.RequiredArgsConstructor;<br><br>@Service<br>@RequiredArgsConstructor<br>public class ReportServiceImpl implements ReportService {<br><br> private static final Logger logger = LoggerFactory.getLogger(ReportServiceImpl.class);<br><br> private final EmployeeRepository employeeRepository;<br><br> /**<br>  * You must create &quot;demo.xlsx&quot; before testing this API<br>  * And enter some data inside the file with 4 columns<br>  */<br> private static final String CSV_FILE_LOCATION = &quot;C:/Users/admin/Documents/demo.xlsx&quot;;<br><br> @Override<br> public Employee saveEmployee(Employee employee) {<br>  return employeeRepository.save(employee);<br> }<br><br> @Override<br> public void generateExcel(HttpServletResponse response) throws Exception {<br><br>  List&lt;Employee&gt; employees = employeeRepository.findAll();<br><br>  HSSFWorkbook workbook = new HSSFWorkbook();<br>  HSSFSheet sheet = workbook.createSheet(&quot;Employees Info&quot;);<br>  HSSFRow row = sheet.createRow(0);<br><br>  row.createCell(0).setCellValue(&quot;ID employee&quot;);<br>  row.createCell(1).setCellValue(&quot;First Name&quot;);<br>  row.createCell(2).setCellValue(&quot;Last Name&quot;);<br>  row.createCell(3).setCellValue(&quot;Started Date&quot;);<br><br>  // Create date cell style<br>  HSSFCellStyle dateCellStyle = workbook.createCellStyle();<br>  HSSFDataFormat dateFormat = workbook.createDataFormat();<br>  // dateCellStyle.setDataFormat(dateFormat.getFormat(&quot;yyyy-mm-dd&quot;));<br>  dateCellStyle.setDataFormat(dateFormat.getFormat(&quot;dd-mm-yyyy&quot;));<br><br>  int dataRowIndex = 1;<br><br>  for (Employee employee : employees) {<br>   HSSFRow dataRow = sheet.createRow(dataRowIndex);<br>   dataRow.createCell(0).setCellValue(employee.getEmployeeId());<br>   dataRow.createCell(1).setCellValue(employee.getFirstName());<br>   dataRow.createCell(2).setCellValue(employee.getLastName());<br><br>   // Set the date value with the date format style<br>   if(employee.getStartedDateInCompany() != null) {<br>    HSSFCell dateCell = dataRow.createCell(3);<br>    dateCell.setCellValue(Date.valueOf(employee.getStartedDateInCompany()));<br>    dateCell.setCellStyle(dateCellStyle);<br>   }<br><br>   dataRowIndex++;<br>  }<br><br>  // Auto-size columns<br>  for (int i = 0; i &lt; 4; i++) {<br>   sheet.autoSizeColumn(i);<br>  }<br><br>  ServletOutputStream ops = response.getOutputStream();<br>  workbook.write(ops);<br>  workbook.close();<br>  ops.close();<br><br> }<br><br> @Override<br> public List&lt;Course&gt; readExcelFile() {<br><br>  List&lt;Course&gt; courses = new ArrayList&lt;&gt;();<br><br>  Workbook workbook = null;<br>  try {<br>   // Creating a Workbook from an Excel file (.xls or .xlsx)<br>   workbook = WorkbookFactory.create(new File(CSV_FILE_LOCATION));<br><br>   // Retrieving the number of sheets in the Workbook<br>   logger.info(&quot;Number of sheets: &quot; + workbook.getNumberOfSheets());<br><br>   // Print all sheets name<br>   workbook.forEach(sheet -&gt; {<br>    logger.info(&quot;Title of sheet =&gt; &quot; + sheet.getSheetName());<br><br>    // Create a DataFormatter to format and get each cell&#39;s value as String<br>    DataFormatter dataFormatter = new DataFormatter();<br><br>    // Loop through all rows and columns and create Course object<br>    int index = 0;<br>    for (Row row : sheet) {<br>     if (index++ == 0)<br>      continue;<br>     Course course = new Course();<br><br>     if (row.getCell(0) != null &amp;&amp; row.getCell(0).getCellType() == CellType.NUMERIC) {<br>      course.setId((int) row.getCell(0).getNumericCellValue());<br>     }<br><br>     if (row.getCell(1) != null) {<br>      course.setName(dataFormatter.formatCellValue(row.getCell(1)));<br>     }<br><br>     Cell dateCell = row.getCell(2);<br>     if (DateUtil.isCellDateFormatted(dateCell)) {<br>      LocalDate date = dateCell.getDateCellValue().toInstant().atZone(ZoneId.systemDefault())<br>        .toLocalDate();<br>      course.setDate(date);<br>     }<br><br>     if (row.getCell(3) != null &amp;&amp; row.getCell(3).getCellType() == CellType.NUMERIC) {<br>      course.setNumber((int) row.getCell(3).getNumericCellValue());<br>     }<br>     courses.add(course);<br>    }<br>   });<br>  } catch (EncryptedDocumentException | IOException e) {<br>   logger.error(e.getMessage(), e);<br>  } finally {<br>   try {<br>    if (workbook != null)<br>     workbook.close();<br>   } catch (IOException e) {<br>    logger.error(e.getMessage(), e);<br>   }<br>  }<br><br>  return courses;<br> }<br><br>}</pre><p>This EmployeeController class defines REST endpoints for managing employees and handling Excel file operations. Here&#39;s a detailed explanation of each part:</p><pre>package bouguern.tuto.demo.controller;<br><br>import org.springframework.http.ResponseEntity;<br>import org.springframework.web.bind.annotation.GetMapping;<br>import org.springframework.web.bind.annotation.PostMapping;<br>import org.springframework.web.bind.annotation.RequestBody;<br>import org.springframework.web.bind.annotation.RequestMapping;<br>import org.springframework.web.bind.annotation.RestController;<br><br>import bouguern.tuto.demo.entity.Course;<br>import bouguern.tuto.demo.entity.Employee;<br>import bouguern.tuto.demo.service.ReportService;<br>import jakarta.servlet.http.HttpServletResponse;<br>import lombok.RequiredArgsConstructor;<br><br>import java.util.List;<br><br>import org.slf4j.Logger;<br>import org.slf4j.LoggerFactory;<br>import org.springframework.web.bind.annotation.ResponseBody;<br><br>@RequestMapping(&quot;/excel&quot;)<br>@RestController<br>@RequiredArgsConstructor<br>public class EmployeeController {<br><br> private static final Logger logger = LoggerFactory.getLogger(EmployeeController.class);<br><br> private final ReportService reportService;<br><br> @PostMapping(&quot;employees&quot;)<br> public ResponseEntity&lt;Employee&gt; createEmployee(@RequestBody Employee employee) {<br>  Employee savedEmployee = reportService.saveEmployee(employee);<br>  logger.info(&quot;Create an employee&quot;);<br>  return ResponseEntity.ok(savedEmployee);<br> }<br><br> @GetMapping(&quot;/write&quot;)<br> public void generateExcelReport(HttpServletResponse response) throws Exception {<br><br>  response.setContentType(&quot;application/octet-stream&quot;);<br><br>  // Excel file will be generated and saved to C:\Users\admin\Downloads as<br>  // &#39;employee.xls&#39;<br><br>  String headerKey = &quot;Content-Disposition&quot;;<br>  String headerValue = &quot;attachment;filename=employees.xls&quot;;<br><br>  response.setHeader(headerKey, headerValue);<br><br>  logger.info(&quot;Generate an Excel file&quot;);<br>  reportService.generateExcel(response);<br><br>  response.flushBuffer();<br> }<br><br> @GetMapping(&quot;/read&quot;)<br> public @ResponseBody List&lt;Course&gt; readCSV() {<br>  logger.info(&quot;Read courses in Excel file and return courses in JSON format&quot;);<br>  return reportService.readExcelFile();<br> }<br>}</pre><h4>Breakdown of the Code:</h4><p><strong>Annotations</strong>:</p><ul><li>@RestController: Indicates that the class is a RESTful web controller. It combines @Controller and @ResponseBody, meaning that return values of methods will be written directly to the HTTP response body as JSON/XML.</li><li>@RequestMapping(&quot;/excel&quot;): Maps HTTP requests to handler methods of MVC and REST controllers. In this case, it sets the base URL path for all endpoints in this controller to /excel.</li><li>@RequiredArgsConstructor: Lombok annotation that generates a constructor with required arguments (i.e., final fields).</li></ul><p><strong>Logger:</strong></p><ul><li>private static final Logger logger = LoggerFactory.getLogger(EmployeeController.class);: Sets up a logger to log messages for the EmployeeController class.</li></ul><p><strong>Dependencies:</strong></p><ul><li>private final ReportService reportService;: Injects the ReportService dependency, which provides the business logic for saving employees, generating Excel reports, and reading Excel files.</li></ul><p><strong>generateExcelReport() Method:</strong></p><ul><li><strong>Endpoint</strong>: GET /excel/write</li><li><strong>Purpose</strong>: Generates an Excel report of employees and writes it to the HTTP response.</li><li><strong>Response</strong>: Sets the content type to application/octet-stream and the content disposition to download the file as employees.xls.</li><li><strong>Logging</strong>: Logs the generation of the Excel file.</li></ul><p><strong>readCSV Method:</strong></p><ul><li><strong>Endpoint</strong>: GET /excel/read</li><li><strong>Purpose</strong>: Reads data from an Excel file and returns it as a list of Course objects in JSON format.</li><li><strong>Response</strong>: Returns the list of Course objects.</li><li><strong>Logging</strong>: Logs the reading of courses from the Excel file.</li></ul><h4>Conclusion</h4><p>In this blog, we’ve explored how to read and write Excel data in a Spring Boot application using Apache POI. We covered the necessary dependencies, implemented the service to handle Excel file operations, and provided endpoints to create employees, generate Excel reports, and read data from Excel files. I hope this guide helps you integrate Excel data handling in your Spring Boot projects efficiently. Happy coding!</p><p>For a detailed view of the complete code and additional functionalities, please visit the <a href="https://github.com/bouguern/spring-boot-read-write-excel-data.git"><strong>GitHub repository</strong></a>. The necessary code snippets and explanations have been provided here, but you can find the full implementation in the repository. Your feedback and contributions are welcome!</p><p>Thank you!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=139753529ebe" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Validating Objects (Entities) in Spring Boot]]></title>
            <link>https://medium.com/@bouguern.mohamed/validating-objects-entities-in-spring-boot-9757fc01211f?source=rss-9126d0af0ba2------2</link>
            <guid isPermaLink="false">https://medium.com/p/9757fc01211f</guid>
            <category><![CDATA[spring-boot-validation]]></category>
            <category><![CDATA[spring-validation]]></category>
            <category><![CDATA[object-oriented]]></category>
            <category><![CDATA[validator]]></category>
            <category><![CDATA[validating]]></category>
            <dc:creator><![CDATA[Mohamed Bouguern]]></dc:creator>
            <pubDate>Mon, 01 Jul 2024 15:55:27 GMT</pubDate>
            <atom:updated>2024-07-01T16:01:50.829Z</atom:updated>
            <content:encoded><![CDATA[<ol><li><strong>Introduction to Validators in Spring Boot 3</strong></li></ol><p>Validation is a crucial aspect of developing robust and secure applications. It ensures that the data flowing through your application meets specific criteria and conforms to the expected formats, thus preventing potential errors and vulnerabilities. In Spring Boot 3, the spring-boot-starter-validation dependency simplifies the process of implementing validation by providing a set of powerful tools and annotations.</p><p><strong>2. What are Validators?</strong></p><p>Validators are components that check the correctness and validity of the data. In the context of a Spring Boot application, validators are typically used to validate user inputs, ensuring that they meet the predefined constraints before processing or persisting them. Spring Boot leverages the Bean Validation API (JSR 380) and the Hibernate Validator as the default implementation to perform validation tasks seamlessly.</p><p><strong>3. Why Use Validators?</strong></p><ul><li><strong>Data Integrity</strong>: Validators help maintain the integrity of data by enforcing rules and constraints, ensuring that only valid data is processed and stored in the database.</li><li><strong>Error Prevention</strong>: By validating input data at an early stage, you can prevent common errors and inconsistencies that might otherwise lead to application crashes or unexpected behavior.</li><li><strong>Security</strong>: Proper validation reduces the risk of security vulnerabilities, such as SQL injection or cross-site scripting (XSS), by ensuring that inputs conform to expected formats and constraints.</li><li><strong>User Experience</strong>: Providing clear validation messages helps users understand what went wrong and how to correct their inputs, improving the overall user experience.</li></ul><p><strong>4. Implementing Validation in Spring Boot 3</strong></p><p>To implement validation in a Spring Boot 3 application, you need to include the spring-boot-starter-validation dependency in your pom.xml file:</p><pre>&lt;dependency&gt;<br>    &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt;<br>    &lt;artifactId&gt;spring-boot-starter-validation&lt;/artifactId&gt;<br>&lt;/dependency&gt;</pre><p>This dependency brings in the necessary libraries and annotations to perform validation tasks efficiently. In the following sections, we’ll explore how to define validation constraints, apply them to your application, and handle validation errors gracefully.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/306/1*nMFLjSPhFqmgJlfoOs1ZAQ.png" /><figcaption>Project Structure</figcaption></figure><p><strong>5. Defining Entities</strong></p><p>In a typical Spring Boot application, entities are the backbone of the data layer. They represent the data structures that are persisted in the database and are annotated with JPA (Jakarta Persistence API) annotations to facilitate ORM (Object-Relational Mapping). In this section, we will define two entities: Post and Comment. These entities will be used to demonstrate how to use validation annotations effectively.</p><p>The Post entity represents a blog post and includes various attributes and relationships. Here is the implementation:</p><pre>package bouguern.tuto.demo.models;<br><br>import java.util.List;<br><br>import jakarta.persistence.CascadeType;<br>import jakarta.persistence.Column;<br>import jakarta.persistence.Entity;<br>import jakarta.persistence.GeneratedValue;<br>import jakarta.persistence.GenerationType;<br>import jakarta.persistence.Id;<br>import jakarta.persistence.OneToMany;<br>import jakarta.validation.constraints.NotBlank;<br>import jakarta.validation.constraints.Size;<br>import lombok.AllArgsConstructor;<br>import lombok.Builder;<br>import lombok.Getter;<br>import lombok.NoArgsConstructor;<br>import lombok.Setter;<br><br>@Setter<br>@Getter<br>@AllArgsConstructor<br>@NoArgsConstructor<br>@Builder<br>@Entity<br>public class Post extends Auditable {<br><br> @Id<br> @GeneratedValue(strategy = GenerationType.IDENTITY)<br> @Column(name = &quot;postId&quot;)<br> private Long postId;<br><br> @NotBlank(message = &quot;The content must not be null and must contain at least one non-whitespace character&quot;)<br> @Size(min = 1, max = 500, message = &quot;content must be at most 500 characters, and has at least one character&quot;)<br> @Column(name = &quot;content&quot;)<br> private String content;<br><br> @OneToMany(mappedBy = &quot;post&quot;, cascade = CascadeType.ALL, orphanRemoval = true)<br> private List&lt;Comment&gt; comments;<br><br>}</pre><ul><li>@Entity: Marks the class as a JPA entity.</li><li>@Id and @GeneratedValue: Denote the primary key of the entity and specify the generation strategy for the ID.</li><li>@Column: Specifies the details of the column to which the field will be mapped.</li><li>@NotBlank and @Size: Validation annotations to ensure the content field is not blank and does not exceed 500 characters.</li><li>@OneToMany: Defines a one-to-many relationship with the Comment entity. The cascade and orphanRemoval attributes manage the lifecycle of related entities.</li></ul><p>The Comment entity represents a comment on a blog post and includes attributes and relationships with the Post entity. Here is the implementation:</p><pre>package bouguern.tuto.demo.models;<br><br>import jakarta.persistence.Column;<br><br>import jakarta.persistence.FetchType;<br><br>import jakarta.persistence.Entity;<br>import jakarta.persistence.GeneratedValue;<br>import jakarta.persistence.GenerationType;<br>import jakarta.persistence.Id;<br>import jakarta.persistence.JoinColumn;<br>import jakarta.persistence.ManyToOne;<br>import jakarta.validation.constraints.NotBlank;<br>import jakarta.validation.constraints.Size;<br>import lombok.AllArgsConstructor;<br>import lombok.Builder;<br>import lombok.Getter;<br>import lombok.NoArgsConstructor;<br>import lombok.Setter;<br><br>@Setter<br>@Getter<br>@AllArgsConstructor<br>@NoArgsConstructor<br>@Builder<br>@Entity<br>public class Comment extends Auditable {<br><br> @Id<br> @GeneratedValue(strategy = GenerationType.IDENTITY)<br> @Column(name = &quot;commentId&quot;)<br> private Long commentId;<br><br> @NotBlank(message = &quot;The comment text must not be null and must contain at least one non-whitespace character&quot;)<br> @Size(min = 1, max = 100, message = &quot;Comment text must be at most 100 characters, and has at least one character&quot;)<br> @Column(name = &quot;text&quot;)<br> private String text;<br><br> @ManyToOne(fetch = FetchType.LAZY)<br> @JoinColumn(name = &quot;post_id&quot;, nullable = false)<br> private Post post;<br>}</pre><ul><li>@Entity: Marks the class as a JPA entity.</li><li>@Id and @GeneratedValue: Denote the primary key of the entity and specify the generation strategy for the ID.</li><li>@Column: Specifies the details of the column to which the field will be mapped.</li><li>@NotBlank and @Size: Validation annotations to ensure the text field is not blank and does not exceed 100 characters.</li><li>@ManyToOne and @JoinColumn: Define a many-to-one relationship with the Post entity, with a foreign key column named post_id.</li></ul><p>By defining these entities and applying validation constraints, we ensure that the data stored in the database meets the necessary requirements. The @NotBlank and @Size annotations help validate the content and text fields of the Post and Comment entities, respectively. This not only improves data integrity but also enhances the overall robustness and security of the application.</p><p><strong>Auditable Class Explanation:</strong></p><p>In a Spring Boot application using JPA (Java Persistence API), the Auditable class plays a crucial role in managing auditing-related functionality for entities. Let&#39;s break down the components and annotations used in this class:</p><ul><li><strong>@EntityListeners(AuditingEntityListener.class)</strong>: This annotation specifies that this entity will be audited using the AuditingEntityListener class. The AuditingEntityListener is responsible for automatically populating auditing-related fields.</li><li><strong>@MappedSuperclass</strong>: Indicates that this class will be mapped to the database, but its attributes will be mapped to the entities that inherit from it. It allows attributes like creationDate and lastModifiedDate to be inherited by other entities without requiring them to define these fields explicitly.</li><li><strong>@Setter and @Getter</strong>: Lombok annotations to automatically generate getter and setter methods for the fields in the class.</li><li><strong>@CreatedDate</strong>: Marks the field creationDate to be automatically populated with the current date and time when an entity is persisted for the first time. It is annotated with @Column to specify database column details such as name, nullability, and updatability.</li><li><strong>@LastModifiedDate</strong>: Marks the field lastModifiedDate to be automatically updated with the current date and time whenever the entity is updated. The insertable = false attribute ensures that this field is not set during the initial insert of the entity but only updated on subsequent modifications.</li><li><strong>LocalDateTime</strong>: Represents date and time information in Java, used here to store timestamps of creationDate and lastModifiedDate.</li></ul><p><strong>Automatic Auditing</strong>: By using Auditable, entities that extend it automatically inherit auditing behavior. This simplifies and standardizes the process of tracking when entities are created (creationDate) and last modified (lastModifiedDate).</p><p><strong>Data Integrity</strong>: Auditing helps in maintaining data integrity by providing insights into when entities were created or updated. This information can be crucial for auditing purposes, versioning, or simply understanding the timeline of data changes.</p><p><strong>Simplified Entity Design</strong>: By abstracting auditing fields into a superclass (Auditable), entity classes can focus on their specific attributes and relationships without cluttering the code with repetitive auditing logic.</p><p><strong>Explanation of </strong><strong>ObjectsValidator Class:</strong></p><p>The ObjectsValidator class in your Spring Boot application serves the purpose of validating objects using the Bean Validation API (JSR 380). Let&#39;s go through each component and functionality of this class:</p><p><strong>@Component</strong>: Indicates that this class is a Spring component and should be automatically detected and registered by the Spring container during component scanning.</p><p><strong>ValidatorFactory and Validator Initialization</strong>:</p><pre>private final ValidatorFactory factory = Validation.buildDefaultValidatorFactory();<br>private final Validator validator = factory.getValidator();</pre><p>Validation.buildDefaultValidatorFactory() initializes a default ValidatorFactory, which is then used to obtain a Validator instance (validator). This setup ensures that the validator is properly configured for performing validation tasks.</p><p>The full code:</p><pre>package bouguern.tuto.demo.validators;<br><br>import java.util.Collections;<br>import java.util.Set;<br>import java.util.stream.Collectors;<br><br>import org.springframework.stereotype.Component;<br><br>import jakarta.validation.ConstraintViolation;<br>import jakarta.validation.Validation;<br>import jakarta.validation.Validator;<br>import jakarta.validation.ValidatorFactory;<br><br>@Component<br>public class ObjectsValidator&lt;T&gt; {<br> <br> private final ValidatorFactory factory = Validation.buildDefaultValidatorFactory();<br> <br> private final Validator validator = factory.getValidator();<br> <br> public Set&lt;String&gt; validate(T objectToValidate) {<br>  <br>  Set&lt;ConstraintViolation&lt;T&gt;&gt; violations = validator.validate(objectToValidate);<br>  <br>  if(!violations.isEmpty()) {<br>   return violations<br>     .stream()<br>     .map(ConstraintViolation::getMessage)<br>     .collect(Collectors.toSet());<br>  }<br>  return Collections.emptySet();<br> }<br><br>}</pre><ul><li>This method accepts an object (objectToValidate) of type T and performs validation using the validator instance.</li><li>validator.validate(objectToValidate) checks the object against defined validation constraints and returns a set of ConstraintViolation instances if any violations are found.</li><li>If violations are found (!violations.isEmpty()), the method maps each violation to its error message using ConstraintViolation::getMessage, collects these messages into a Set&lt;String&gt;, and returns it.</li><li>If no violations are found, Collections.emptySet() is returned, indicating that the object is valid according to the defined constraints.</li><li>The method utilizes Java streams (stream(), map(), collect()) to process and transform the validation results efficiently. This approach leverages functional programming principles to handle collections of validation errors succinctly.</li></ul><p><strong>Important!</strong> By using generics (&lt;T&gt;),ObjectsValidator class can validate any type of object that you specify when using the validator. This makes the validator adaptable to a wide range of domain objects within your application without needing to create separate validator classes for each type (Avoiding Code Duplication).</p><p>Now, let’s create PostServiceImpl Class:</p><pre>package bouguern.tuto.demo.services;<br><br>import java.time.LocalDateTime;<br><br>import org.springframework.stereotype.Service;<br>import org.springframework.transaction.annotation.Transactional;<br><br>import bouguern.tuto.demo.dtos.PostDto;<br>import bouguern.tuto.demo.mappers.PostMapper;<br>import bouguern.tuto.demo.repository.PostRepository;<br>import bouguern.tuto.demo.validators.ObjectsValidator;<br>import lombok.RequiredArgsConstructor;<br><br>@Service<br>@RequiredArgsConstructor<br>public class PostServiceImpl implements PostService {<br><br> private final PostRepository postRepository;<br><br> private final ObjectsValidator&lt;PostDto&gt; postValidator;<br><br> @Override<br> @Transactional<br> public String savePost(PostDto postDto) {<br><br>  postDto.setCreationDate(LocalDateTime.now());<br>  postDto.setLastModifiedDate(LocalDateTime.now());<br><br>  var violations = postValidator.validate(postDto);<br><br>  if (!violations.isEmpty()) {<br><br>   return String.join(&quot;\n&quot;, violations);<br>  }<br><br>  postRepository.save(PostMapper.toPostEntity(postDto));<br><br>  final String commentMessage = &quot;POST Validated and Saved&quot;;<br><br>  return commentMessage;<br> }<br><br>}</pre><ul><li><strong>@Service</strong>: Indicates that this class is a service component in the Spring framework. It is used to encapsulate business logic and is typically injected into controllers or other services.</li><li><strong>@RequiredArgsConstructor</strong>: Lombok annotation that generates a constructor with required arguments for all final fields. In this case, it ensures that postRepository and postValidator are automatically injected via constructor injection.</li><li><strong>@Transactional</strong>: Annotation provided by Spring that ensures that a method is wrapped with a transaction. This means that if any part of the method fails, all changes made within the method are rolled back, maintaining data consistency.</li><li>ObjectsValidator&lt;PostDto&gt; (postValidator): An instance of ObjectsValidator specifically configured to validate PostDto objects.</li></ul><p>If you’d like the full code, please check out my <a href="https://github.com/bouguern/spring-boot-validate-objects.git"><strong>GitHub repository</strong></a>.</p><p><strong>6. Purpose and Benefits:</strong></p><ul><li><strong>Reusable Validation Logic</strong>: ObjectsValidator provides a reusable component for validating any type T of object that supports Bean Validation annotations (@NotBlank, @Size, etc.). This promotes code reusability and reduces duplication across the application.</li><li><strong>Integration with Spring</strong>: Being a Spring component (@Component), ObjectsValidator can be injected into other Spring-managed beans or components, facilitating easy integration into your application&#39;s service layer or controllers.</li><li><strong>Error Handling and Messaging</strong>: By collecting and returning validation error messages (Set&lt;String&gt;), the class ensures that detailed feedback about validation failures is available, enhancing the user experience and aiding in debugging.</li><li><strong>Configuration Flexibility</strong>: The use of Validation.buildDefaultValidatorFactory() ensures that the validator is configured with default settings suitable for most applications. Additional customization can be achieved through alternative configurations of ValidatorFactory.</li><li><strong>Separation of Concerns</strong>: The PostServiceImpl class separates business logic (savePost method) from validation (postValidator) and persistence (postRepository), adhering to the principles of clean architecture and maintainable code.</li><li><strong>Validation</strong>: By using postValidator, the service class ensures that incoming PostDto objects are validated against defined constraints (@NotBlank, @Size, etc.) before attempting to persist them, reducing the risk of invalid data entering the system.</li><li><strong>Integration with DTOs</strong>: The use of PostDto (Data Transfer Object) allows the service to handle and validate data coming from external sources or UI layers before converting and persisting it as Post entities.</li></ul><p><strong>7. Run the App</strong></p><p>When running the application and making POST requests to http://localhost:9095/create-post with different payloads, here&#39;s what each scenario entails based on the provided examples:</p><p><strong>Scenario 1:</strong></p><pre>POST http://localhost:9095/create-post<br><br>Content-Type: application/json<br><br>{<br>    &quot;content&quot;: &quot;First Post&quot;<br>}</pre><p><strong>Expected Response:</strong></p><ul><li><strong>Status Code:</strong> 202 Accepted</li><li><strong>Response Body:</strong> “POST Validated and Saved”</li></ul><p><strong>Scenario 2</strong>:</p><pre>POST http://localhost:9095/create-post<br><br>Content-Type: application/json<br><br>{<br>    &quot;content&quot;: &quot;&quot;<br>}</pre><p><strong>Expected Response:</strong></p><ul><li><strong>Status Code:</strong> 202 Accepted</li><li><strong>Response Body:</strong> “The content must not be null and must contain at least one non-whitespace character” and “ content must be at most 500 characters, and has at least one character”</li><li>The request body contains an empty string for content, which violates the @NotBlank and @Size constraints. Therefore, the request is still accepted (202 Accepted), but the server responds with a detailed error message listing the validation issues related to the content field.</li></ul><p><strong>Scenario 3:</strong></p><pre>POST http://localhost:9095/create-post<br><br>Content-Type: application/json<br><br>{<br>    &quot;content&quot;: &quot; &quot; // just space<br>}</pre><p><strong>Expected Response:</strong></p><ul><li><strong>Status Code:</strong> 202 Accepted</li><li><strong>Response Body:</strong> “The content must not be null and must contain at least one non-whitespace character”</li><li>The request body contains a space character for content, which is considered as whitespace and doesn&#39;t meet the @NotBlank constraint. Therefore, the request is accepted (202 Accepted), and the server responds with an error message specifying that the content must not be null and must contain at least one non-whitespace character.</li></ul><p><strong>Summary</strong>:</p><p>In all scenarios, the server responds with a 202 Accepted status code, indicating that the request was successfully received and accepted. The response body varies based on the content provided:</p><ul><li>If the content is valid (Scenario 1), it confirms successful validation and saving.</li><li>If the content is empty (Scenario 2) or contains only whitespace (Scenario 3), it provides detailed error messages explaining the validation issues.</li></ul><p>These responses help users understand the outcome of their requests and provide clear feedback on validation errors when applicable.</p><p>If you’d like the full code, please check out my <a href="https://github.com/bouguern/spring-boot-validate-objects.git"><strong>GitHub repository</strong></a>.</p><p>Thank you for following along with this guide! For the rest of the code and even more Spring Boot magic, hop over to my <a href="https://github.com/bouguern"><strong>GitHub</strong></a><strong>.</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9757fc01211f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Configure Multiple Data Sources -Postgres & MySQL in a Spring Boot 3]]></title>
            <link>https://medium.com/@bouguern.mohamed/configure-multiple-data-sources-postgres-mysql-in-a-spring-boot-3-03f67e45c287?source=rss-9126d0af0ba2------2</link>
            <guid isPermaLink="false">https://medium.com/p/03f67e45c287</guid>
            <category><![CDATA[multiple-datasources]]></category>
            <category><![CDATA[postgresql]]></category>
            <category><![CDATA[exception-handling]]></category>
            <category><![CDATA[mysql]]></category>
            <category><![CDATA[spring-boot]]></category>
            <dc:creator><![CDATA[Mohamed Bouguern]]></dc:creator>
            <pubDate>Mon, 01 Jul 2024 13:14:03 GMT</pubDate>
            <atom:updated>2024-07-01T13:14:03.024Z</atom:updated>
            <content:encoded><![CDATA[<p>You heard that right. You can connect to multiple databases from a single Spring Boot app.</p><p>In this tutorial, we’ll implement a Spring Boot configuration for a Spring Data JPA system with multiple databases (MySQL and Postgres).</p><p>Before going further in this tutorial, we will look at the common terminology such as what and why we use multiple databases.</p><h4><strong>1. What is database integration?</strong></h4><p>Database integration involves combining multiple databases and their associated applications into a single, unified system. This process allows different databases to work together seamlessly, facilitating data sharing, consolidation, and management across various platforms and systems. Database integration is crucial for businesses and organizations that need to ensure consistent, accurate, and timely access to data from different sources.</p><p>In either case, the goal is to improve information sharing, efficiency, and decision-making across your organization. Integration also helps to safeguard your data’s validity, integrity, and security, as well as the performance of any tools that are based around it.</p><p>Additionally, integration can be used to provide more convenient data management processes. For instance, by enabling your team to carry out admin tasks on several databases, from a single tool.</p><p>Consolidating databases can also offer performance benefits. For example, by allowing you to access the same information by querying a single, centralized database.</p><h4>2. Why integrate multiple databases?</h4><ul><li>Querying multiple databases for one application achieving many of the benefits of integration, without the need to migrate data.</li><li>It helps create a centralized repository where all relevant data is available, ensuring consistency and reliability.</li><li>Teams can collaborate more effectively when they have access to integrated data, facilitating better communication and coordination.</li><li>Integrated systems can include data validation and cleaning processes, enhancing overall data quality.</li><li>Organizations can leverage integrated data to perform advanced analytics, uncover trends, and generate actionable insights.</li><li>With integrated customer data, organizations can offer more personalized services and improve customer satisfaction.</li><li>Integrated systems can be more easily scaled and adapted to accommodate new data sources, business units, or changes in business requirements.</li><li>Integrated systems ensure that data protection measures are consistently applied across all data sources.</li><li>To support multiple organizations within the same app. Based on the user login, you can dynamically decide which organization’s database their data should go into and which database would store the more common information.</li></ul><h4>3. Here, tools Used on this app and Project Structure:</h4><p>We are using Spring Boot 3.3.0, JDK 17, and Maven. In case you’re confused about where you should create the corresponding files or folder, let us review the project structure of the spring boot application:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/482/1*-38ixwTwGtwm4n5ntSWHOA.png" /><figcaption>Project Structure</figcaption></figure><h4>4. Let us start building the application!</h4><p>Here, we specify the dependencies for the Spring Boot (Web, JPA, and Configuration processor), Postgres and Mysql databases, and Lombok. Maven will automatically resolve the other dependencies. The pom.xml file will have the following code:</p><pre>&lt;?xml version=&quot;1.0&quot; encoding=&quot;UTF-8&quot;?&gt;<br>&lt;project xmlns=&quot;http://maven.apache.org/POM/4.0.0&quot;<br> xmlns:xsi=&quot;http://www.w3.org/2001/XMLSchema-instance&quot;<br> xsi:schemaLocation=&quot;http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd&quot;&gt;<br> &lt;modelVersion&gt;4.0.0&lt;/modelVersion&gt;<br> &lt;parent&gt;<br>  &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt;<br>  &lt;artifactId&gt;spring-boot-starter-parent&lt;/artifactId&gt;<br>  &lt;version&gt;3.3.0&lt;/version&gt;<br>  &lt;relativePath /&gt; &lt;!-- lookup parent from repository --&gt;<br> &lt;/parent&gt;<br> &lt;groupId&gt;bouguern.tuto&lt;/groupId&gt;<br> &lt;artifactId&gt;spring-boot-multi-DB-config&lt;/artifactId&gt;<br> &lt;version&gt;0.0.1&lt;/version&gt;<br> &lt;name&gt;spring-boot-multi-DB-config&lt;/name&gt;<br> &lt;description&gt;<br>  Multi-DB Configurator is a robust and user-friendly <br>  Spring Boot application designed to facilitate seamless configuration <br>  and management of multiple databases within a single Spring Boot project. <br>  This app is ideal for developers and organizations that need to interact <br>  with different databases, offering a unified interface and streamlined process <br>  to handle complex data requirements efficiently.<br> &lt;/description&gt;<br> &lt;properties&gt;<br>  &lt;java.version&gt;17&lt;/java.version&gt;<br> &lt;/properties&gt;<br> &lt;dependencies&gt;<br>  &lt;dependency&gt;<br>   &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt;<br>   &lt;artifactId&gt;spring-boot-starter-data-jpa&lt;/artifactId&gt;<br>  &lt;/dependency&gt;<br>  &lt;dependency&gt;<br>   &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt;<br>   &lt;artifactId&gt;spring-boot-starter-web&lt;/artifactId&gt;<br>  &lt;/dependency&gt;<br><br>  &lt;dependency&gt;<br>   &lt;groupId&gt;org.postgresql&lt;/groupId&gt;<br>   &lt;artifactId&gt;postgresql&lt;/artifactId&gt;<br>  &lt;/dependency&gt;<br>  &lt;dependency&gt;<br>   &lt;groupId&gt;com.mysql&lt;/groupId&gt;<br>   &lt;artifactId&gt;mysql-connector-j&lt;/artifactId&gt;<br>  &lt;/dependency&gt;<br>  &lt;dependency&gt;<br>   &lt;groupId&gt;org.projectlombok&lt;/groupId&gt;<br>   &lt;artifactId&gt;lombok&lt;/artifactId&gt;<br>   &lt;optional&gt;true&lt;/optional&gt;<br>  &lt;/dependency&gt;<br>  &lt;dependency&gt;<br>   &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt;<br>   &lt;artifactId&gt;spring-boot-starter-test&lt;/artifactId&gt;<br>   &lt;scope&gt;test&lt;/scope&gt;<br>  &lt;/dependency&gt;<br>  &lt;dependency&gt;<br>   &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt;<br>   &lt;artifactId&gt;spring-boot-configuration-processor&lt;/artifactId&gt;<br>   &lt;optional&gt;true&lt;/optional&gt;<br>  &lt;/dependency&gt;<br> &lt;/dependencies&gt;<br><br> &lt;build&gt;<br>  &lt;plugins&gt;<br>   &lt;plugin&gt;<br>    &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt;<br>    &lt;artifactId&gt;spring-boot-maven-plugin&lt;/artifactId&gt;<br>    &lt;configuration&gt;<br>     &lt;excludes&gt;<br>      &lt;exclude&gt;<br>       &lt;groupId&gt;org.projectlombok&lt;/groupId&gt;<br>       &lt;artifactId&gt;lombok&lt;/artifactId&gt;<br>      &lt;/exclude&gt;<br>     &lt;/excludes&gt;<br>    &lt;/configuration&gt;<br>   &lt;/plugin&gt;<br>  &lt;/plugins&gt;<br> &lt;/build&gt;<br><br>&lt;/project&gt;</pre><p>Let’s create two entities (User and Product), with each living in a separate database.</p><p>Remember will only configure two classes here to build a concrete understanding for this tutorial, User entity will be in MySQL DB and Product entity will be in Postgres DB.</p><p>Here is the User entity:</p><pre>package bouguern.tuto.demo.user;<br><br>import java.time.LocalDate;<br><br>import jakarta.persistence.GeneratedValue;<br>import jakarta.persistence.GenerationType;<br>import jakarta.persistence.Id;<br>import jakarta.persistence.Entity;<br><br>import lombok.AllArgsConstructor;<br>import lombok.Builder;<br>import lombok.Getter;<br>import lombok.NoArgsConstructor;<br>import lombok.Setter;<br><br>@Setter<br>@Getter<br>@AllArgsConstructor<br>@NoArgsConstructor<br>@Builder<br>@Entity<br>public class User {<br><br> @Id<br> @GeneratedValue(strategy = GenerationType.IDENTITY)<br> private Long userId;<br> private String username;<br> private LocalDate birthDay;<br><br>}</pre><p>And here’s the entity Product:</p><pre>package bouguern.tuto.demo.product;<br><br>import jakarta.persistence.Entity;<br>import jakarta.persistence.GeneratedValue;<br>import jakarta.persistence.GenerationType;<br>import jakarta.persistence.Id;<br>import lombok.AllArgsConstructor;<br>import lombok.Builder;<br>import lombok.Getter;<br>import lombok.NoArgsConstructor;<br>import lombok.Setter;<br><br>@Setter<br>@Getter<br>@AllArgsConstructor<br>@NoArgsConstructor<br>@Builder<br>@Entity<br>public class Product {<br> <br> @Id<br> @GeneratedValue(strategy = GenerationType.IDENTITY)<br> private Long productId;<br> private String name;<br><br>}</pre><p>We can see that the two entities are also placed in <strong>independent packages</strong>. This will be <strong>important </strong>as we move into the configuration.</p><p>Next, let’s take a look at our two JPA repositories, UserRepository:</p><pre>package bouguern.tuto.demo.user;<br><br>import org.springframework.data.jpa.repository.JpaRepository;<br>import org.springframework.stereotype.Repository;<br><br>@Repository<br>public interface UserRepository extends JpaRepository&lt;User, Long&gt;{<br><br>}</pre><p>And ProductRepository:</p><pre>package bouguern.tuto.demo.product;<br><br>import org.springframework.data.jpa.repository.JpaRepository;<br>import org.springframework.stereotype.Repository;<br><br>@Repository<br>public interface ProductRepository extends JpaRepository&lt;Product, Long&gt; {<br><br>}</pre><p>Note again how we created these two repositories in <strong>different packages</strong>.</p><p>Ensure that <strong>entity and repository</strong> classes that connect to db1 or db2 should belong to a <strong>different package</strong>.</p><p>Now we’ll get to the actual Spring configuration. We’ll first set up two configuration classes — one for the User and the other for the Product.</p><p>In each configuration class, will define the Spring bean for the data source, Entity Manager Factory, and Transaction Manager.</p><p>At the top of this configuration class, we will add the <a href="http://twitter.com/EnableJpaRepositorie">@EnableJpaRepositorie</a>s annotation with the basePackages attribute. In this property, we will define the package that contains the JPA repository class for this particular data source.</p><p>The UserDBConfig:</p><pre>package bouguern.tuto.demo.DBConfig;<br><br>import java.util.HashMap;<br><br>import javax.sql.DataSource;<br><br>import org.springframework.beans.factory.annotation.Qualifier;<br>import org.springframework.boot.context.properties.ConfigurationProperties;<br>import org.springframework.boot.jdbc.DataSourceBuilder;<br>import org.springframework.boot.orm.jpa.EntityManagerFactoryBuilder;<br>import org.springframework.context.annotation.Bean;<br>import org.springframework.context.annotation.Configuration;<br>import org.springframework.context.annotation.Primary;<br>import org.springframework.data.jpa.repository.config.EnableJpaRepositories;<br>import org.springframework.orm.jpa.JpaTransactionManager;<br>import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;<br>import org.springframework.transaction.PlatformTransactionManager;<br>import org.springframework.transaction.annotation.EnableTransactionManagement;<br><br>import jakarta.persistence.EntityManagerFactory;<br><br><br>@Configuration<br>@EnableJpaRepositories(<br>  entityManagerFactoryRef = &quot;db1EntityManagerFactory&quot;, <br>  transactionManagerRef = &quot;db1TransactionManager&quot;,<br>  basePackages = { &quot;bouguern.tuto.demo.user&quot; })<br>@EnableTransactionManagement<br>public class UserDBConfig {<br> <br> @Primary<br> @Bean(name = &quot;dataSource1&quot;)<br> @ConfigurationProperties(prefix = &quot;spring.db1.datasource&quot;)<br> DataSource dataSource() {<br>  return DataSourceBuilder.create().build();<br> }<br><br> @Primary<br> @Bean(name = &quot;db1EntityManagerFactory&quot;)<br> LocalContainerEntityManagerFactoryBean db1EntityManagerFactory(final EntityManagerFactoryBuilder builder,<br>   @Qualifier(&quot;dataSource1&quot;) DataSource dataSource) {<br>  <br>  final HashMap&lt;String, String&gt; properties = new HashMap&lt;&gt;();<br>  properties.put(&quot;hibernate.hbm2ddl.auto&quot;, &quot;update&quot;);<br>  //properties.put(&quot;hibernate.dialect&quot;, &quot;org.hibernate.dialect.MariaDBDialect&quot;);<br><br>  return builder.dataSource(dataSource)<br>       .properties(properties)<br>       .packages(&quot;bouguern.tuto.demo.user&quot;)<br>       .persistenceUnit(&quot;user&quot;)<br>       .build();<br> }<br><br> @Primary<br> @Bean(name = &quot;db1TransactionManager&quot;)<br> PlatformTransactionManager db1TransactionManager(@Qualifier(&quot;db1EntityManagerFactory&quot;) final EntityManagerFactory entityManagerFactory) {<br>  return new JpaTransactionManager(entityManagerFactory);<br> }<br><br>}</pre><p>The ProductDBConfig:</p><pre>package bouguern.tuto.demo.DBConfig;<br><br>import java.util.HashMap;<br><br>import javax.sql.DataSource;<br><br>import org.springframework.beans.factory.annotation.Qualifier;<br>import org.springframework.boot.context.properties.ConfigurationProperties;<br>import org.springframework.boot.jdbc.DataSourceBuilder;<br>import org.springframework.boot.orm.jpa.EntityManagerFactoryBuilder;<br>import org.springframework.context.annotation.Bean;<br>import org.springframework.context.annotation.Configuration;<br>import org.springframework.data.jpa.repository.config.EnableJpaRepositories;<br>import org.springframework.orm.jpa.JpaTransactionManager;<br>import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;<br>import org.springframework.transaction.PlatformTransactionManager;<br>import org.springframework.transaction.annotation.EnableTransactionManagement;<br><br>import jakarta.persistence.EntityManagerFactory;<br><br>@Configuration<br>@EnableJpaRepositories(entityManagerFactoryRef = &quot;db2EntityManagerFactory&quot;, transactionManagerRef = &quot;db2TransactionManager&quot;, basePackages = {<br>  &quot;bouguern.tuto.demo.product&quot; })<br>@EnableTransactionManagement<br>public class ProductDBConfig {<br><br> @Bean(name = &quot;db2DataSource&quot;)<br> @ConfigurationProperties(prefix = &quot;spring.db2.datasource&quot;)<br> DataSource dataSource() {<br>  return DataSourceBuilder.create().build();<br> }<br><br> @Bean(name = &quot;db2EntityManagerFactory&quot;)<br> LocalContainerEntityManagerFactoryBean db2EntityManagerFactory(final EntityManagerFactoryBuilder builder,<br>   @Qualifier(&quot;db2DataSource&quot;) final DataSource dataSource) {<br><br>  final HashMap&lt;String, String&gt; properties = new HashMap&lt;&gt;();<br>  properties.put(&quot;hibernate.hbm2ddl.auto&quot;, &quot;update&quot;);<br>  return builder.dataSource(dataSource).properties(properties).packages(&quot;bouguern.tuto.demo.product&quot;)<br>    .persistenceUnit(&quot;product&quot;).build();<br> }<br><br> @Bean(name = &quot;db2TransactionManager&quot;)<br> PlatformTransactionManager db2TransactionManager(<br>   @Qualifier(&quot;db2EntityManagerFactory&quot;) final EntityManagerFactory entityManagerFactory) {<br>  return new JpaTransactionManager(entityManagerFactory);<br> }<br><br>}</pre><p>. The <strong>dataSource()</strong> method which is annotated with the <a href="http://twitter.com/ConfigurationPropert">@<strong>ConfigurationPropert</strong></a><strong>ies </strong>annotation. The annotation has a prefix property which tells the spring that the properties for this data source are prefixed with the given value and should be used for creating the data source instance. The properties are read from the application.properties file.</p><p>. The <strong>db1EntityManagerFactory()</strong> method is responsible for creating the <strong>LocalContainerEntityManagerFactoryBean </strong>instance for the data source.</p><p>. The <strong>db1TransactionManager()</strong> method is responsible for creating the <strong>PlatformTransactionManager </strong>instance for this data source to handle the transaction management.</p><p>. Also, the use of <a href="http://twitter.com/Primary">@<strong>Primary</strong></a><strong> </strong>annotation in this class tells Spring to treat the bean instances defined in this class as the primary beans.</p><p>. Notice how we use the <strong>userTransactionManager </strong>as our <strong>Primary TransactionManager </strong>by annotating the bean definition with <a href="http://twitter.com/Primary">@<strong>Primary</strong></a>. That’s helpful whenever we’re going to implicitly or explicitly inject the transaction manager without specifying which one by name.</p><p>. The interesting part is annotating the data source bean creation method with <a href="http://twitter.com/ConfigurationPropert">@<strong>ConfigurationPropert</strong></a><strong>ies</strong>. We just need to specify the corresponding config prefix. Inside this method, we’re using a <strong>DataSourceBuilder</strong>, and Spring Boot will automatically take care of the rest.</p><p>Here we will define the two data sources for Postgres and Mysql databases along with database and <strong>application properties</strong>:</p><pre>spring.application.name=spring-boot-multi-DB-config<br>server.port=9095<br><br>## MySQL<br>spring.db1.datasource.jdbc-url=jdbc:mysql://localhost:3306/userDB?createDatabaseIfNotExist=true<br>spring.db1.datasource.username=root<br>spring.db1.datasource.password=root<br>spring.db1.datasource.driver-class-name=com.mysql.cj.jdbc.Driver<br><br><br>## PostgresSQL<br>## Postgres does not support createDatabaseIfNotExist=true, <br>## so you need to create the &#39;productDB&#39; database in Postgres before running the app.<br>spring.db2.datasource.jdbc-url=jdbc:postgresql://localhost:5432/productDB<br>spring.db2.datasource.username=postgres<br>spring.db2.datasource.password=postgres<br>spring.db2.datasource.driver-class-name=org.postgresql.Driver<br><br>spring.jpa.show-sql=true<br>spring.jpa.hibernate.ddl-auto=update</pre><p><strong>Conculsion</strong></p><p>In this blog post, we covered the essential steps to configure multiple databases in a Spring Boot application, including:</p><p>— Defining Entities</p><p>— Creating Repositories</p><p>— Configuring Datasources</p><p>— Setting up the application.properties</p><p>For the complete code and additional configurations (services, exception handlings, and controllers), please visit my <a href="https://github.com/bouguern/spring-boot-multi-DB-config.git"><strong>GitHub Repository</strong></a><strong>.</strong></p><p>This is a Maven-based project, so it should be easy to import and run as it is.</p><p>Thank you for following along with this guide! For the rest of the code and even more Spring Boot magic, hop over to my <a href="https://github.com/bouguern">GitHub </a>and let’s continue this coding adventure together!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=03f67e45c287" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>