<?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 Mohd Aamir  on Medium]]></title>
        <description><![CDATA[Stories by Mohd Aamir  on Medium]]></description>
        <link>https://medium.com/@Mohd_Aamir_17?source=rss-e48f7cb59ea8------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*U9jaJka3TyIrOLpMSDVToA.jpeg</url>
            <title>Stories by Mohd Aamir  on Medium</title>
            <link>https://medium.com/@Mohd_Aamir_17?source=rss-e48f7cb59ea8------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Wed, 18 Nov 2026 10:20:11 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@Mohd_Aamir_17/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[The Hidden Pitfalls of Immutability in Java: A Deep Dive]]></title>
            <link>https://medium.com/@Mohd_Aamir_17/the-hidden-pitfalls-of-immutability-in-java-a-deep-dive-28692cd4412e?source=rss-e48f7cb59ea8------2</link>
            <guid isPermaLink="false">https://medium.com/p/28692cd4412e</guid>
            <category><![CDATA[java]]></category>
            <category><![CDATA[technology]]></category>
            <category><![CDATA[learning]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[spring-boot]]></category>
            <dc:creator><![CDATA[Mohd Aamir ]]></dc:creator>
            <pubDate>Mon, 02 Feb 2026 17:54:13 GMT</pubDate>
            <atom:updated>2026-02-02T17:54:13.566Z</atom:updated>
            <content:encoded><![CDATA[<p><em>Why your “immutable” class might not be as immutable as you think</em></p><p>Immutability in Java seems simple… until you try to implement it correctly. I recently came across a piece of code that perfectly illustrates the subtle mistakes developers make when trying to create immutable classes. Let me take you through this journey.</p><h3>The Deceptive Code</h3><p>Take a look at this class:</p><pre>public class Test {<br>    private int i;</pre><pre>    Test(int i) {<br>        this.i = i;<br>    }</pre><pre>    public Test modify(int i) {<br>        if (this.i == i) {<br>            return this;<br>        } else {<br>            return new Test(i);<br>        }<br>    }<br>}</pre><p>At first glance, it looks immutable. The modify() method doesn’t change the existing object—it returns a new one. The field is private. What could go wrong?</p><p><strong>Everything.</strong></p><h3>What Is Immutability, Really?</h3><p>An immutable class is one whose instances <strong>cannot be modified after creation</strong>. Once an object is created, its state stays constant throughout its lifetime.</p><p>Java’s String class is a perfect example. When you “modify” a string, you actually get a new object—the original remains unchanged.</p><p>The benefits of immutability include:</p><ul><li><strong>Thread safety</strong> — No synchronization required</li><li><strong>Caching</strong> — Safe to reuse instances</li><li><strong>Predictability</strong> — No unexpected state changes</li><li><strong>Security</strong> — Cannot be tampered with after creation</li></ul><h3>The Three Fatal Flaws</h3><p>Our Test class violates three key rules of immutability:</p><h3>Flaw #1: Non-Final Fields</h3><pre>private int i;  // Danger!</pre><p>Without the final keyword, this field is technically mutable. Reflection can even bypass private access and change it.</p><p><strong>Fix:</strong></p><pre>private final int i;</pre><p>The final keyword ensures the field can only be assigned once, during construction.</p><h3>Flaw #2: Non-Final Class</h3><pre>public class Test {  // Can be extended!</pre><p>Someone could extend your class and override modify() to mutate the object:</p><pre>public class MutableTest extends Test {<br>    MutableTest(int i) {<br>        super(i);<br>    }</pre><pre>    @Override<br>    public Test modify(int i) {<br>        // Use reflection to modify the field<br>        return this;  // Breaks immutability!<br>    }<br>}</pre><p><strong>Fix:</strong></p><pre>public final class Test { }</pre><p>Marking the class as final prevents inheritance, closing this loophole.</p><h3>Flaw #3: No Public Accessors</h3><p>Currently, there’s no way to read the value of i:</p><pre>// How do I get the value of i?</pre><p>Immutable classes should provide <strong>getter methods</strong> — they are safe since fields can’t be modified.</p><p><strong>Fix:</strong></p><pre>public int getI() {<br>    return i;<br>}</pre><h3>The Correct Implementation</h3><pre>public final class Test {<br>    private final int i;</pre><pre>    Test(int i) {<br>        this.i = i;<br>    }</pre><pre>    public int getI() {<br>        return i;<br>    }</pre><pre>    public Test modify(int i) {<br>        if (this.i == i) {<br>            return this;<br>        } else {<br>            return new Test(i);<br>        }<br>    }<br>}</pre><h3>The Elegant Optimization</h3><p>Notice this pattern:</p><pre>public Test modify(int i) {<br>    if (this.i == i) {<br>        return this;  // Brilliant!<br>    } else {<br>        return new Test(i);<br>    }<br>}</pre><p>This is called <strong>instance caching</strong> or a <strong>flyweight pattern</strong>. When the new value equals the current value, we return the existing instance instead of creating a new one.</p><p>Java’s String.intern(), Integer.valueOf(), and Boolean.valueOf() all use this technique. It saves memory and improves performance while keeping immutability guarantees.</p><pre>Test t1 = new Test(10);<br>Test t2 = t1.modify(100);<br>Test t3 = t1.modify(10);</pre><pre>System.out.println(t1 == t2);  // false (different values)<br>System.out.println(t1 == t3);  // true (same value, same instance!)</pre><h3>The Immutability Checklist</h3><p>When creating an immutable class in Java, ensure you:</p><ol><li>Mark the class as final</li><li>Mark all fields as private final</li><li>Initialize all fields in the constructor</li><li>Provide no setters</li><li>Don’t allow methods to modify fields</li><li>For mutable field types (collections, dates), return defensive copies</li><li>Consider instance caching for efficiency</li><li>Initialize all fields in the constructor</li></ol><h3>Beyond Primitives: The Mutable Field Challenge</h3><p>Using primitives is easy, but mutable objects require care:</p><pre>public final class Person {<br>    private final String name;<br>    private final List&lt;String&gt; hobbies;</pre><pre>public Person(String name, List&lt;String&gt; hobbies) {<br>        this.name = name;<br>        this.hobbies = hobbies;  // Danger!<br>    }<br>    public List&lt;String&gt; getHobbies() {<br>        return hobbies;  // Unsafe!<br>    }<br>}</pre><p>Even though hobbies is final, the list itself is mutable. Anyone can call getHobbies().add(&quot;hacking&quot;) and mutate your object.</p><p><strong>Correct approach:</strong></p><pre>public final class Person {<br>    private final String name;<br>    private final List&lt;String&gt; hobbies;</pre><pre>public Person(String name, List&lt;String&gt; hobbies) {<br>        this.name = name;<br>        this.hobbies = List.copyOf(hobbies);  // Defensive copy<br>    }<br>    public List&lt;String&gt; getHobbies() {<br>        return hobbies;  // Safe, unmodifiable<br>    }<br>}</pre><h3>Modern Java: Records to the Rescue</h3><p>Java 14 introduced <strong>records</strong>, which automatically create immutable classes:</p><pre>public record Test(int i) {<br>    public Test modify(int i) {<br>        if (this.i == i) {<br>            return this;<br>        } else {<br>            return new Test(i);<br>        }<br>    }<br>}</pre><p>Records automatically:</p><ul><li>Make the class final</li><li>Make fields private final</li><li>Generate constructors, getters, equals(), hashCode(), and toString()</li></ul><p>You still need <strong>defensive copies</strong> for mutable fields manually.</p><h3>Why This Matters</h3><p>You might think, “This is academic. Who cares?”</p><p>But immutability bugs have <strong>real consequences</strong>:</p><ul><li><strong>Concurrency bugs</strong> — “Mostly immutable” objects fail under concurrent load</li><li><strong>Security vulnerabilities</strong> — Mutable objects can be modified by untrusted code</li><li><strong>Cache corruption</strong> — Objects assumed immutable can corrupt caches</li><li><strong>Debugging nightmares</strong> — Tracking state changes in mutable objects is hard</li></ul><h3>The Bottom Line</h3><p>Creating truly immutable classes in Java requires attention to detail. Avoiding setters or returning new instances isn’t enough.</p><p><strong>Key points:</strong></p><ul><li>final keyword on class and fields</li><li>Defensive copying for mutable fields</li><li>Careful API design to prevent modification</li></ul><p>Once you get these principles right, the benefits — thread safety, simplicity, and reliability — are immense.</p><blockquote><em>Immutability isn’t just about preventing change. It’s about creating guarantees that make your code robust, maintainable, and correct.</em></blockquote><p><em>Have you encountered subtle bugs with “almost immutable” classes in Java? Share your stories in the comments below!</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=28692cd4412e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Rate Limiting in Spring Boot: Your API’s First Line of Defense]]></title>
            <link>https://medium.com/@Mohd_Aamir_17/rate-limiting-in-spring-boot-your-apis-first-line-of-defense-46b2340c1920?source=rss-e48f7cb59ea8------2</link>
            <guid isPermaLink="false">https://medium.com/p/46b2340c1920</guid>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[spring-security]]></category>
            <category><![CDATA[spring-boot]]></category>
            <category><![CDATA[spring-framework]]></category>
            <dc:creator><![CDATA[Mohd Aamir ]]></dc:creator>
            <pubDate>Tue, 20 Jan 2026 13:12:22 GMT</pubDate>
            <atom:updated>2026-01-20T13:12:22.737Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/810/1*XLGyu_sIDebMjfccjWa1_w.png" /></figure><p><em>How to protect your APIs from brute-force attacks, DDoS attempts, and resource abuse — without breaking a sweat</em></p><p>Picture this: It’s 3 AM, and your phone buzzes. Your production API is down. The culprit? A single rogue client bombarding your login endpoint with thousands of requests per second. Your server is gasping for air, legitimate users are locked out, and your on-call nightmare has just begun.</p><p><strong>This is preventable.</strong></p><p>Welcome to the world of rate limiting — the unsung hero of API security. In this guide, I’ll show you how to implement production-ready rate limiting in Spring Boot using Bucket4j, the smart way.</p><h3>Why Rate Limiting Matters (More Than You Think)</h3><p>Rate limiting isn’t just about blocking too many requests. It’s your defense against:</p><p>🛡️ <strong>Brute-force attacks</strong> on authentication endpoints<br>🚫 <strong>DDoS attacks</strong> that can cripple your infrastructure<br>⚖️ <strong>Resource hogging</strong> by abusive or buggy clients<br>💰 <strong>Unexpected cloud bills</strong> from API abuse<br>🎯 <strong>Fair usage</strong> enforcement across user tiers (Free vs. Premium)</p><p>Without rate limiting, you’re leaving your API’s front door wide open.</p><h3>The Token Bucket Algorithm: Simple but Powerful</h3><p>Before we dive into code, understand the elegance of the <strong>token bucket algorithm</strong>:</p><p>Imagine a physical bucket that:</p><ol><li><strong>Holds tokens</strong> (each representing one allowed request)</li><li><strong>Refills gradually</strong> over time at a configured rate</li><li><strong>Requires a token</strong> for each API request</li><li><strong>Rejects requests</strong> when empty</li></ol><p><strong>Why this matters:</strong> Unlike simple counters, token buckets handle burst traffic gracefully while maintaining long-term rate controls.</p><h3>Getting Started: Dependencies</h3><p>Add Bucket4j and Caffeine cache to your Spring Boot project:</p><pre>&lt;dependency&gt;<br>    &lt;groupId&gt;com.bucket4j&lt;/groupId&gt;<br>    &lt;artifactId&gt;bucket4j-core&lt;/artifactId&gt;<br>    &lt;version&gt;8.10.1&lt;/version&gt;<br>&lt;/dependency&gt;</pre><pre>&lt;dependency&gt;<br>    &lt;groupId&gt;com.github.ben-manes.caffeine&lt;/groupId&gt;<br>    &lt;artifactId&gt;caffeine&lt;/artifactId&gt;<br>    &lt;version&gt;3.1.8&lt;/version&gt;<br>&lt;/dependency&gt;</pre><p><strong>Why Caffeine?</strong> It’s Google’s high-performance cache with automatic eviction — preventing memory leaks from abandoned client sessions.</p><h3>Approach #1: Filter-Based (The Production Standard)</h3><p>Spring Boot filters intercept <strong>every request</strong> before it reaches your controllers. This means bulletproof protection that can’t be bypassed.</p><h3>The Key Implementation Details</h3><p>Here’s what makes a production-ready filter:</p><p><strong>1. Per-Client Buckets</strong></p><pre>// Never share buckets! Each IP gets its own<br>Cache&lt;String, Bucket&gt; authBuckets = Caffeine.newBuilder()<br>    .expireAfterAccess(10, TimeUnit.MINUTES)<br>    .maximumSize(100_000)<br>    .build();</pre><p><strong>2. Different Limits for Different Endpoints</strong></p><pre>// Auth endpoints: Strict (5 req/min)<br>// API endpoints: Lenient (100 req/hour)<br>if (uri.startsWith(&quot;/api/auth&quot;)) {<br>    bucket = authBuckets.get(clientId, this::createAuthBucket);<br>} else {<br>    bucket = apiBuckets.get(clientId, this::createApiBucket);<br>}</pre><p><strong>3. Smart Client Identification</strong></p><pre>// Handle reverse proxies correctly<br>String xff = request.getHeader(&quot;X-Forwarded-For&quot;);<br>String clientId = (xff != null) ? xff.split(&quot;,&quot;)[0] : request.getRemoteAddr();</pre><p><strong>4. RFC-Compliant Headers</strong></p><pre>response.setHeader(&quot;X-RateLimit-Limit&quot;, &quot;100&quot;);<br>response.setHeader(&quot;X-RateLimit-Remaining&quot;, &quot;47&quot;);<br>response.setHeader(&quot;X-RateLimit-Reset&quot;, &quot;1642350000&quot;);<br>response.setHeader(&quot;Retry-After&quot;, &quot;58&quot;); // seconds until reset</pre><p><strong>5. Skip Logic for Special Cases</strong></p><pre>// Don&#39;t rate limit:<br>// - OPTIONS requests (CORS preflight)<br>// - Health checks (/actuator, /health)<br>// - Static resources (CSS, JS, images)</pre><h3>Why This Approach Rocks</h3><p>✅ Centralized — protects every endpoint automatically<br>✅ Caffeine cache — zero memory leaks, auto-eviction<br>✅ Proxy-aware — works behind load balancers<br>✅ Helpful errors — tells clients when to retry</p><h3>Approach #2: Annotation-Based (The Developer’s Favorite)</h3><p>For fine-grained control, use custom annotations:</p><pre>@RateLimit(limit = 5, duration = 1, timeUnit = TimeUnit.MINUTES)<br>@PostMapping(&quot;/login&quot;)<br>public ResponseEntity&lt;?&gt; login(@RequestBody LoginRequest request) {<br>    // Your login logic<br>}</pre><p><strong>The magic:</strong> An AOP aspect intercepts annotated methods, checking rate limits before execution. Clean. Declarative. Beautiful.</p><p><strong>When to use this:</strong> Multiple endpoints with wildly different limits (login vs. password reset vs. profile updates).</p><h3>Configuration: Never Hardcode Limits</h3><p>One of the biggest production mistakes? Hardcoded rate limits.</p><p>What happens when you need to adjust during a traffic spike? <strong>Code deploy</strong>.<br>What if you’re under attack? <strong>Another deploy</strong>.</p><p>Don’t do this to yourself:</p><pre># application.yml<br>rate-limit:<br>  enabled: true<br>  auth:<br>    limit: 5<br>    duration-minutes: 1<br>  api:<br>    limit: 100<br>    duration-minutes: 60</pre><p>Now you can change limits with a config update — no deployment needed.</p><h3>The Refill Strategy That Matters</h3><p>Bucket4j offers two refill modes:</p><pre>// GREEDY: All tokens refill at once (dangerous!)<br>Refill.greedy(10, Duration.ofMinutes(1))</pre><pre>// INTERVALLY: Tokens refill gradually (recommended)<br>Refill.intervally(10, Duration.ofMinutes(1))</pre><p><strong>Why intervally?</strong> Prevents burst attacks. Instead of 10 tokens appearing all at once every minute, clients get ~1 token every 6 seconds. Much safer for authentication endpoints.</p><h3>Common Mistakes (I’ve Made Them All)</h3><p>The MistakeWhy It’s DangerousThe FixShared bucket for all clientsOne bad client blocks everyonePer-IP/user bucketsUnbounded ConcurrentHashMapMemory leak → 3 AM crashCaffeine with TTLIgnoring X-Forwarded-ForAll clients = same IPParse proxy headersRate limiting OPTIONSBreaks CORSSkip OPTIONS requestsNo Retry-After headerClients spam retriesRFC 6585 complianceHardcoded limitsRequires deploy to adjustConfiguration files</p><h3>Testing: Prove It Works</h3><pre>@Test<br>void shouldBlockAfterRateLimit() throws Exception {<br>    // Make 10 successful requests<br>    for (int i = 0; i &lt; 10; i++) {<br>        mockMvc.perform(get(&quot;/api/data&quot;))<br>            .andExpect(status().isOk());<br>    }<br>    <br>    // 11th request should be blocked<br>    mockMvc.perform(get(&quot;/api/data&quot;))<br>        .andExpect(status().isTooManyRequests())<br>        .andExpect(header().exists(&quot;Retry-After&quot;));<br>}</pre><p>Always test boundary conditions — the exact limit, one over, and window reset behavior.</p><h3>Decision Matrix: Which Approach?</h3><p>Your SituationBest ApproachWhySingle server appFilter + CaffeineSimple, fast, zero dependenciesMicroservices (multi-instance)Filter + RedisShared state across instancesFine-grained endpoint controlAnnotations + CaffeineReadable, declarativeTiered pricing (Free/Pro)Filter + User contextUser-aware buckets</p><h3>Production Deployment Checklist</h3><p>Before you ship:</p><ul><li>Load test with realistic traffic patterns</li><li>Tune limits for each endpoint type (auth vs. read vs. write)</li><li>Set up alerts for high rejection rates</li><li>Document limits in API docs (developers need to know!)</li><li>Test CORS with your actual frontend</li><li>Log blocked requests for forensics</li><li>Create runbooks for adjusting limits during incidents</li></ul><h3>Key Takeaways</h3><p><strong>1. Always use per-client buckets</strong> — Never share across clients<br><strong>2. Use bounded caches</strong> — Prevent OOM with Caffeine eviction<br><strong>3. Provide helpful responses</strong> — Include Retry-After headers<br><strong>4. Monitor everything</strong> — Track rejected requests, tune limits<br><strong>5. Test thoroughly</strong> — Boundary conditions matter</p><h3>The Philosophy Behind Good Rate Limiting</h3><p>Rate limiting isn’t just code — it’s a <strong>philosophy of responsible API design</strong>:</p><ul><li><strong>Security-first:</strong> Protect auth endpoints aggressively</li><li><strong>User experience:</strong> Tell clients <em>when</em> to retry, not just “no”</li><li><strong>Operational awareness:</strong> Monitor and tune based on real traffic</li><li><strong>Business alignment:</strong> Your rate limits encode your pricing model</li><li><strong>Defense in depth:</strong> One layer among many (combine with auth, validation, WAF)</li></ul><h3>Your Turn</h3><p>You now have the knowledge to protect your APIs properly.</p><p><strong>Start conservative.</strong> It’s easier to loosen limits than tighten them after users adapt.</p><p><strong>Monitor relentlessly.</strong> Set up dashboards showing rejections per endpoint, top blocked IPs, and bucket utilization.</p><p><strong>Document everything.</strong> Your API docs should clearly state rate limits for each endpoint.</p><h3>Resources</h3><ul><li><a href="https://github.com/bucket4j/bucket4j">Bucket4j GitHub</a> — Official documentation</li><li><a href="https://tools.ietf.org/html/rfc6585">RFC 6585</a> — HTTP 429 specification</li><li><a href="https://cheatsheetseries.owasp.org/">OWASP Rate Limiting</a> — Security best practices</li></ul><p><strong>Found this helpful?</strong> Share it with your team. Rate limiting is one of those things everyone <em>means</em> to implement properly… someday. Make today that day.</p><p><strong>Questions?</strong> Drop them in the comments. Let’s discuss your specific rate limiting challenges.</p><p>Stay secure 🔒 Keep building 🚀</p><p><em>Implementing rate limiting in your Spring Boot app? What’s your biggest challenge? Share in the comments below.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=46b2340c1920" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Mastering JPQL and Spring Data JPA Queries: A Practical Guide]]></title>
            <link>https://medium.com/@Mohd_Aamir_17/mastering-jpql-and-spring-data-jpa-queries-a-practical-guide-b33d8705fc69?source=rss-e48f7cb59ea8------2</link>
            <guid isPermaLink="false">https://medium.com/p/b33d8705fc69</guid>
            <category><![CDATA[jpa]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[personal-development]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[spring-boot]]></category>
            <dc:creator><![CDATA[Mohd Aamir ]]></dc:creator>
            <pubDate>Thu, 18 Dec 2025 10:30:43 GMT</pubDate>
            <atom:updated>2025-12-18T10:30:43.497Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/534/1*Rpg2pEyBfenAnbwm96dEpg.png" /><figcaption>A visual guide to Spring Data JPA queries: Derived Queries, JPQL, Native Queries, and Specifications with dynamic filters and sorting</figcaption></figure><p>Spring Data JPA is one of the most powerful tools in the Spring ecosystem, enabling developers to interact with relational databases in a clean, object-oriented way. One of the core features of Spring Data JPA is <strong>JPQL (Java Persistence Query Language)</strong> and the ability to write <strong>custom queries</strong>. In this article, we’ll explore how to use JPQL and Spring Data JPA queries effectively, with practical examples using an Employee entity.</p><h3>What is JPQL?</h3><p>JPQL stands for <strong>Java Persistence Query Language</strong>, and it’s similar to SQL, but instead of querying database tables directly, it queries <strong>entities and their fields</strong>. This makes it database-agnostic, safe, and tightly integrated with JPA.</p><p>Example:</p><pre>@Query(&quot;SELECT e FROM Employee e WHERE e.salary &gt; :minSalary&quot;)<br>List&lt;Employee&gt; findHighSalaryEmployees(@Param(&quot;minSalary&quot;) Double minSalary);</pre><p>Here:</p><ul><li>Employee is an <strong>entity class</strong>, not a table.</li><li>e.salary is a <strong>field in the Employee entity</strong>, not the database column.</li></ul><p>JPQL queries are automatically translated by JPA into native SQL for the underlying database.</p><h3>Spring Data JPA Query Options</h3><p>Spring Data JPA provides <strong>three ways to query your database</strong>:</p><p>1.<strong>Derived Query Methods</strong></p><p>Spring can automatically generate queries from <strong>method names</strong>. This is great for simple filters.</p><p>Example :</p><pre>List&lt;Employee&gt; findByDepartmentId(Long departmentId);<br><br>List&lt;Employee&gt; findBySalaryBetween(Double minSalary, Double maxSalary);<br><br>List&lt;Employee&gt; findByNameContainingIgnoreCase(String searchText);</pre><ul><li>No @Query annotation is required.</li><li>Clean and readable for straightforward conditions.</li></ul><h3>2. JPQL with @Query</h3><p>For more complex queries, you can write JPQL using the @Query annotation.</p><p><strong>Example 1: Filter by department and salary</strong></p><pre>@Query(&quot;SELECT e FROM Employee e WHERE e.department.id = :deptId AND e.salary &gt; :minSalary&quot;)<br>List&lt;Employee&gt; findEmployeesByDeptAndMinSalary(@Param(&quot;deptId&quot;) Long deptId,<br>                                               @Param(&quot;minSalary&quot;) Double minSalary);</pre><p><strong>Example 2: Join with related entities</strong></p><pre>@Query(&quot;SELECT e FROM Employee e JOIN e.department d WHERE d.name = :deptName&quot;)<br>List&lt;Employee&gt; findEmployeesByDepartmentName(@Param(&quot;deptName&quot;) String deptName);</pre><ul><li>Joins can be used with @ManyToOne, @OneToMany, @OneToOne relationships.</li><li>Works perfectly for <strong>entity relationships</strong> without writing raw SQL.</li></ul><h3>3 .Native SQL Queries</h3><p>Sometimes JPQL can’t express a query easily, especially with database-specific functions. In that case, you can write <strong>native SQL queries</strong>.</p><pre>@Query(value = &quot;SELECT * FROM employees e WHERE e.year_of_joining &gt;= :year&quot;, nativeQuery = true)<br>List&lt;Employee&gt; findEmployeesByJoiningYear(@Param(&quot;year&quot;) Integer year);</pre><ul><li>Use only when JPQL is insufficient.</li><li>Returns entities, but you can also use projections or DTOs for efficiency.</li></ul><h3>Sorting and Pagination</h3><p>Spring Data JPA integrates JPQL and query methods with <strong>pagination and sorting</strong>.</p><pre>Page&lt;Employee&gt; findByDepartmentId(Long departmentId, Pageable pageable);<br><br>@Query(&quot;SELECT e FROM Employee e WHERE e.salary &gt; :minSalary&quot;)<br>Page&lt;Employee&gt; findHighSalaryEmployees(@Param(&quot;minSalary&quot;) Double minSalary, Pageable pageable);</pre><ul><li>Pageable allows <strong>page number, page size, and sort order</strong>.</li><li>Returns a Page&lt;Employee&gt; containing content, total pages, total elements, and more.</li></ul><h3>Pro Tip: Using DTOs for Queries</h3><p>Instead of returning entities directly, you can map query results to <strong>DTOs</strong>. This is especially important for large tables:</p><pre>@Query(&quot;SELECT new com.example.dto.EmployeeResponseDto(e.id, e.name, e.salary, e.department.name) &quot; +<br>       &quot;FROM Employee e WHERE e.salary &gt; :minSalary&quot;)<br>List&lt;EmployeeResponseDto&gt; findHighSalaryEmployeesDto(@Param(&quot;minSalary&quot;) Double minSalary);</pre><ul><li>Reduces data transfer overhead.</li><li>Keeps your API responses clean.</li></ul><h3>Advanced Filters with Specifications</h3><p>While JPQL is great for static queries, <strong>Spring Data Specifications</strong> allow <strong>dynamic filtering</strong>:</p><ul><li>Optional filters (e.g., department, designation, gender)</li><li>OR conditions (name OR email search)</li><li>Ranges (salary, yearOfJoining)</li><li>Multi-field sorting</li></ul><pre>Specification&lt;Employee&gt; spec = EmployeeSpecification.getEmployeeSpecification(<br>    departmentIds, designationIds, gender, searchText, minSalary, maxSalary, minYear, maxYear<br>);<br><br>Page&lt;Employee&gt; page = employeeRepository.findAll(spec, pageable);</pre><p>This approach is <strong>flexible and scalable</strong>, perfect for enterprise APIs.</p><p>💡 <strong>Pro Tip:</strong> Always start with <strong>derived queries</strong> for simple cases, use <strong>JPQL</strong> for joins or advanced logic, and <strong>Specifications</strong> when filters are dynamic and optional.</p><h3>Key Takeaways</h3><ul><li>Derived queries → simple, fast, no annotations needed.</li><li>JPQL → entity-based queries, great for joins and advanced filters.</li><li>Native queries → database-specific SQL when needed.</li><li>Specifications → optional and dynamic filters, multi-field sorting.</li><li>DTOs → return only what’s needed, avoid exposing entities.</li></ul><h3>Hands-On Practice</h3><ol><li>Build a <strong>dynamic employee search API</strong> with filters and multi-field sorting.</li><li>Map query results to <strong>DTOs</strong> for cleaner API responses.</li><li>Combine JPQL and Specifications for complex, production-ready queries.</li></ol><h3>Conclusion</h3><p>JPQL and Spring Data JPA queries are <strong>powerful tools</strong> for building robust, maintainable database-driven applications. Here’s what we learned:</p><ol><li>JPQL queries operate on <strong>entities</strong>, not tables.</li><li>Derived query methods are great for simple queries</li><li>Use @Query for complex JPQL queries or native SQL.</li><li>Pagination and sorting integrate seamlessly with Spring Data.</li><li>Map results to <strong>DTOs</strong> for clean API responses.</li><li>Specifications allow <strong>dynamic and advanced filtering.</strong></li></ol><p>With these tools, you can build <strong>flexible, type-safe, and efficient database queries</strong> without sacrificing maintainability.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b33d8705fc69" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to Prevent Inserts, Updates, and Deletes in JPA using Entity Listeners]]></title>
            <link>https://medium.com/@Mohd_Aamir_17/how-to-prevent-inserts-updates-and-deletes-in-jpa-using-entity-listeners-dfaf6cebb376?source=rss-e48f7cb59ea8------2</link>
            <guid isPermaLink="false">https://medium.com/p/dfaf6cebb376</guid>
            <category><![CDATA[spring-boot]]></category>
            <category><![CDATA[spring]]></category>
            <category><![CDATA[development]]></category>
            <category><![CDATA[skills]]></category>
            <category><![CDATA[java]]></category>
            <dc:creator><![CDATA[Mohd Aamir ]]></dc:creator>
            <pubDate>Fri, 11 Apr 2025 19:45:10 GMT</pubDate>
            <atom:updated>2025-04-11T19:45:10.896Z</atom:updated>
            <content:encoded><![CDATA[<p>In most applications using <strong>JPA</strong> or <strong>Hibernate</strong>, we focus a lot on <em>how</em> to persist data — how to create, update, and delete entities. But have you ever come across a use case where you actually <strong>don’t want</strong> certain entities to be modified at all?</p><p>Maybe it’s a legacy table, a read-only configuration entity, or audit data that should never be touched once written. Whatever the case, it’s entirely valid to want JPA to <strong>read only</strong> — no insert, no update, no delete.</p><p>In this article, I’ll show you a simple yet powerful way to <strong>block these operations</strong> using JPA lifecycle events.</p><p><strong>The Use Case</strong></p><p>I was working on a system where a certain table was <strong>meant to be read-only</strong> — strictly used for querying and referencing. However, because we were using Spring Data JPA with repositories, there was still a chance that someone might accidentally call:</p><pre>repository.save(entity);</pre><p>Or even:</p><pre>repository.delete(entity);</pre><p>Both of which would silently modify the database — something we definitely didn’t want.</p><p>To prevent this, I implemented a lightweight <strong>entity listener</strong> that throws an exception whenever JPA tries to persist, update, or remove a certain entity.</p><p><strong>The Code</strong></p><p>Here’s the full class:</p><pre>import jakarta.persistence.PrePersist;<br>import jakarta.persistence.PreRemove;<br>import jakarta.persistence.PreUpdate;<br><br>public class PreventAnyInsertUpdate {<br><br>    @PrePersist<br>    void onPersist(Object o) {<br>        throw new IllegalStateException(&quot;JPA is trying to persist an entity of type &quot; + (o == null ? &quot;null&quot; : o.getClass()));<br>    }<br><br>    @PreUpdate<br>    void onUpdate(Object o) {<br>        throw new IllegalStateException(&quot;JPA is trying to update an entity of type &quot; + (o == null ? &quot;null&quot; : o.getClass()));<br>    }<br><br>    @PreRemove<br>    void onPreRemove(Object o) {<br>        throw new IllegalStateException(&quot;JPA is trying to remove an entity of type &quot; + (o == null ? &quot;null&quot; : o.getClass()));<br>    }<br>}</pre><p>Each method corresponds to a JPA <strong>lifecycle callback</strong>:</p><ul><li>@PrePersist: Called before an entity is inserted</li><li>@PreUpdate: Called before an entity is updated</li><li>@PreRemove: Called before an entity is deleted</li></ul><p>Whenever any of these operations are triggered by JPA, the code throws an IllegalStateException—effectively blocking the operation.</p><p><strong>How to Use It</strong></p><p>To apply this listener to any entity, just annotate it with @EntityListeners:</p><pre>import jakarta.persistence.*;<br><br>@Entity<br>@EntityListeners(PreventAnyInsertUpdate.class)<br>public class ReadOnlyEntity {<br><br>    @Id<br>    private Long id;<br><br>    private String configKey;<br><br>    private String configValue;<br><br>    // Getters and setters<br>}</pre><p>That’s it! From now on, JPA will raise an exception if it tries to persist, update, or delete instances of ReadOnlyEntity.</p><p><strong>Why Not Just Use </strong><strong>@Immutable?</strong></p><p>Hibernate offers an annotation called @Immutable, which can be used like this:</p><pre>@Immutable<br>@Entity<br>public class ReadOnlyEntity { ... }</pre><p>This <strong>disables dirty checking</strong> and tells Hibernate not to perform updates. However, it doesn’t stop inserts or deletes completely. Also, this approach is <strong>Hibernate-specific</strong>, whereas using entity listeners works with <strong>standard JPA</strong>.</p><p>Entity listeners give you <strong>more control and clarity</strong>, with the ability to log, throw specific exceptions, or even conditionally allow/block operations.</p><p><strong>Bonus: Apply to Multiple Entities</strong></p><p>You can use this same listener for multiple entities — just annotate each with @EntityListeners(PreventAnyInsertUpdate.class).</p><p>You could even apply it conditionally using a base class or configuration logic, depending on your needs.</p><h3>A Few Gotchas</h3><ul><li>This approach <strong>only works for JPA-managed operations</strong>. It won’t prevent someone from running raw SQL or JDBC updates.</li><li>The error message can (and should) be customized to match your application’s exception-handling strategy.</li><li>If you apply this to an entity accidentally, you’ll start seeing exceptions like:<br> &quot;JPA is trying to update an entity of type class com.example.MyEntity&quot;<br> … which is kind of the point. 😄</li></ul><h3>Summary</h3><p>Sometimes, the best way to manage data is to <strong>protect it from being changed</strong>.</p><p>With JPA lifecycle callbacks, you can:</p><ul><li>Safely intercept insert, update, and delete operations</li><li>Throw meaningful exceptions to stop them</li><li>Make your entities <strong>read-only at runtime</strong> without relying on database permissions or external rules</li></ul><p>This technique is easy to implement, fully portable, and adds an extra layer of safety — especially in larger codebases where mistakes can be costly.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=dfaf6cebb376" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to Disable the Conditions Evaluation Report in Spring Boot]]></title>
            <link>https://medium.com/@Mohd_Aamir_17/how-to-disable-the-conditions-evaluation-report-in-spring-boot-35ee606669c5?source=rss-e48f7cb59ea8------2</link>
            <guid isPermaLink="false">https://medium.com/p/35ee606669c5</guid>
            <category><![CDATA[developer]]></category>
            <category><![CDATA[spring-framework]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[development]]></category>
            <category><![CDATA[spring-boot]]></category>
            <dc:creator><![CDATA[Mohd Aamir ]]></dc:creator>
            <pubDate>Mon, 16 Dec 2024 07:27:50 GMT</pubDate>
            <atom:updated>2024-12-16T07:27:50.374Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*ZRoe--57fLrx2x12.png" /></figure><p>Spring Boot provides a robust auto-configuration feature that evaluates various conditions during application startup. As part of this process, Spring Boot logs a <strong>Conditions Evaluation Report</strong>, offering insights into which configuration conditions were met or failed. While this report is helpful during development and debugging, it may clutter logs in production or when detailed logs are unnecessary.</p><p>In this article, we’ll explore how to disable the <strong>Conditions Evaluation Report</strong> in Spring Boot, along with its advantages and disadvantages.</p><h3>What Is the Conditions Evaluation Report?</h3><p>The <strong>Conditions Evaluation Report</strong> is a diagnostic tool that logs detailed information about Spring Boot’s auto-configuration process. It shows:</p><ul><li>Active auto-configuration classes</li><li>Conditions that were evaluated</li><li>Whether a configuration was applied or ignored</li></ul><p>Example log output:</p><pre>============================<br>CONDITIONS EVALUATION REPORT<br>============================<br>Positive matches:<br>-----------------<br>   DataSourceAutoConfiguration matched</pre><pre>Negative matches:<br>-----------------<br>   MongoAutoConfiguration did not match</pre><h3>Why Disable It?</h3><p>You might want to disable the <strong>Conditions Evaluation Report</strong> to:</p><ul><li>Reduce log verbosity in production environments.</li><li>Minimize startup log output for cleaner monitoring.</li><li>Prevent sensitive configuration details from appearing in logs.</li></ul><h3>How to Disable the Conditions Evaluation Report</h3><h3>1. Disable Debug Logging</h3><p>The debug=true property in application.properties or application.yml enables extensive startup logs, including the Conditions Evaluation Report.</p><p><strong>Solution:</strong> Set it to false or remove it:</p><pre># Disable debug logs<br>debug=false</pre><h3>2. Adjust Logging Level</h3><p>To disable auto-configuration logs specifically, adjust the logging level:</p><pre># Disable auto-configuration logs<br>logging.level.org.springframework.boot.autoconfigure=OFF</pre><h3>3. Suppress the Banner Display</h3><p>Spring Boot’s startup banner sometimes triggers additional startup details. Disable it by adding:</p><pre># Disable Spring Boot banner<br>spring.main.banner-mode=off</pre><h3>4. Disable Through Main Class</h3><p>Another method is disabling startup information programmatically:</p><pre>import org.springframework.boot.SpringApplication;<br>import org.springframework.boot.autoconfigure.SpringBootApplication;<br><br>@SpringBootApplication<br>public class Application {<br>    public static void main(String[] args) {<br>       SpringApplication app = new SpringApplication(Application.class);<br>       app.setLogStartupInfo(false);  // Disable Conditions Evaluation Report<br>       app.run(args);<br>    }<br>}</pre><h3>5. Use Specific Profiles</h3><p>Spring Boot supports profiles like dev, test, or prod. Using a profile other than dev may reduce logging output:</p><pre># Activate production profile<br>spring.profiles.active=prod</pre><h3>Advantages of Disabling the Conditions Evaluation Report</h3><ol><li><strong>Cleaner Logs:</strong> Reduces log clutter, making logs easier to read.</li></ol><p><strong>2. Enhanced Security:</strong> Sensitive configuration details are not logged.</p><p><strong>3. Improved Performance:</strong> Slightly faster startup as fewer details are processed and logged.</p><h3>Disadvantages of Disabling the Conditions Evaluation Report</h3><ol><li><strong>Limited Debugging Information:</strong> Troubleshooting becomes harder without detailed logs.</li></ol><p><strong>2. Reduced Transparency:</strong> You lose insights into which configurations were applied or ignored.</p><p><strong>3. Development Slowdown:</strong> Developers may need to re-enable detailed logs to diagnose configuration issues.</p><h3>Final Thoughts</h3><p>The <strong>Conditions Evaluation Report</strong> is a valuable tool for understanding how Spring Boot configures applications. However, in production environments or clean monitoring setups, it can create unnecessary log noise. By following the methods outlined in this article, you can easily disable the report and manage your Spring Boot application’s logging behavior effectively.</p><p>Let me know if you found this guide helpful or need additional details!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=35ee606669c5" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Streamlining Entity Class Creation: Solving Developer Pain Points with Automated Bean Generation]]></title>
            <link>https://medium.com/@Mohd_Aamir_17/streamlining-entity-class-creation-solving-developer-pain-points-with-automated-bean-generation-f7a922924a50?source=rss-e48f7cb59ea8------2</link>
            <guid isPermaLink="false">https://medium.com/p/f7a922924a50</guid>
            <category><![CDATA[java]]></category>
            <category><![CDATA[spring]]></category>
            <category><![CDATA[developer]]></category>
            <category><![CDATA[development]]></category>
            <category><![CDATA[spring-boot]]></category>
            <dc:creator><![CDATA[Mohd Aamir ]]></dc:creator>
            <pubDate>Sun, 01 Dec 2024 20:32:15 GMT</pubDate>
            <atom:updated>2024-12-01T20:32:15.747Z</atom:updated>
            <content:encoded><![CDATA[<h3>Introduction</h3><p>In Java application development, especially in enterprise-level applications that use frameworks like Spring Boot, developers often face challenges when creating entity classes (or beans) that map database tables to Java objects. This process, while straightforward in concept, can become tedious, error-prone, and time-consuming in practice. This article explores the common drawbacks of manually creating beans, the pitfalls developers encounter, and how an automated approach, like the one showcased in this code example, can save time and improve code quality.</p><h3>The Problem: Challenges in Manual Bean Creation</h3><h4>1. Error-Prone Process</h4><p>Developers must manually map database table columns to Java variables. A minor mistake, such as a typo or incorrect type mapping, can lead to runtime errors or unexpected behavior.<br><strong>Example:</strong><br>Mistakenly mapping a bytea column in PostgreSQL to String instead of byte[] can break functionality when handling binary data.</p><h4>2. Time-Consuming for Large Schemas</h4><p>Large schemas with numerous tables and columns increase the likelihood of human errors. Writing boilerplate annotations like @Column and @Id for every column adds unnecessary overhead.</p><h4>3. Inconsistent Naming Conventions</h4><p>Column names in databases are often snake_case, while Java variables follow camelCase. Ensuring consistent and meaningful conversions manually can be taxing.</p><h4>4. Type Mapping Complexity</h4><p>Each database has its own type system. For instance:</p><ul><li>PostgreSQL uses types like int4, int8, timestamptz, and bytea.</li><li>Developers need to know how these map to Java types (Integer, Long, Timestamp, byte[]).</li></ul><p>Forgetting or misinterpreting mappings can lead to runtime issues.</p><h4>5. Missed Annotations</h4><p>Forgetting to annotate primary key fields with @Id or relationships with @OneToMany can lead to issues when working with ORM frameworks like Hibernate.</p><h3>The Solution: Automated Entity Class Generation</h3><p>To address these challenges, the provided code demonstrates an automated entity class generator. This utility simplifies the process by dynamically creating classes with the correct annotations, mappings, and naming conventions.</p><h3>How It Works: Code Example</h3><p>Below is a utility class, EntityGenerator, that automates the creation of entity classes:</p><pre>package com.mind.ccd.util;<br><br>import org.springframework.beans.factory.annotation.Value;<br>import org.springframework.stereotype.Service;<br><br>import java.io.File;<br>import java.io.FileWriter;<br>import java.sql.Connection;<br>import java.sql.DatabaseMetaData;<br>import java.sql.DriverManager;<br>import java.sql.ResultSet;<br><br>@Service<br>public class EntityGenerator {<br><br>    @Value(&quot;${spring.datasource.url}&quot;)<br>    private String dbUrl;<br><br>    @Value(&quot;${spring.datasource.username}&quot;)<br>    private String dbUsername;<br><br>    @Value(&quot;${spring.datasource.password}&quot;)<br>    private String dbPassword;<br><br>    public void generateEntityClass(String tableName, String packageName, String outputDir, String schemaName) {<br>        try (Connection connection = DriverManager.getConnection(dbUrl, dbUsername, dbPassword)) {<br>            DatabaseMetaData metaData = connection.getMetaData();<br>            ResultSet columns = metaData.getColumns(null, schemaName, tableName, null);<br>            ResultSet primaryKeys = metaData.getPrimaryKeys(null, schemaName, tableName);<br><br>            // Determine the primary keys<br>            StringBuilder primaryKeyColumns = new StringBuilder();<br>            while (primaryKeys.next()) {<br>                primaryKeyColumns.append(primaryKeys.getString(&quot;COLUMN_NAME&quot;)).append(&quot;,&quot;);<br>            }<br>            String primaryKey = primaryKeyColumns.length() &gt; 0 ? primaryKeyColumns.substring(0, primaryKeyColumns.length() - 1) : &quot;&quot;;<br><br>            // Capitalize table name for class name<br>            String className = capitalize(tableName);<br><br>            StringBuilder classBuilder = new StringBuilder();<br><br>            // Package declaration<br>            classBuilder.append(&quot;package &quot;).append(packageName).append(&quot;;\n\n&quot;);<br>            classBuilder.append(&quot;import jakarta.persistence.*;\n&quot;);<br>            classBuilder.append(&quot;import java.sql.Timestamp;\n&quot;);<br>            classBuilder.append(&quot;import lombok.Data;\n\n&quot;);<br>            classBuilder.append(&quot;@Data\n&quot;);<br>            classBuilder.append(&quot;@Entity\n&quot;);<br>            classBuilder.append(&quot;@Table(name = \&quot;&quot;).append(tableName).append(&quot;\&quot;, schema = \&quot;&quot;)<br>                    .append(schemaName).append(&quot;\&quot;)\n&quot;);<br>            classBuilder.append(&quot;public class &quot;).append(className).append(&quot; {\n\n&quot;);<br><br>            // Process columns<br>            while (columns.next()) {<br>                String columnName = columns.getString(&quot;COLUMN_NAME&quot;);<br>                String dataType = columns.getString(&quot;TYPE_NAME&quot;);<br><br>                // Convert SQL type to Java type<br>                String javaType = mapToJavaType(dataType);<br><br>                // Check if this column is a primary key<br>                if (primaryKey.contains(columnName)) {<br>                    classBuilder.append(&quot;    @Id\n&quot;);<br>                }<br><br>                // Add field<br>                classBuilder.append(&quot;    @Column(name = \&quot;&quot;).append(columnName).append(&quot;\&quot;)\n&quot;);<br>                classBuilder.append(&quot;    private &quot;).append(javaType).append(&quot; &quot;).append(toCamelCase(columnName)).append(&quot;;\n\n&quot;);<br>            }<br><br>            classBuilder.append(&quot;}&quot;);<br><br>            // Ensure the output directory exists<br>            File directory = new File(outputDir);<br>            if (!directory.exists()) {<br>                boolean dirsCreated = directory.mkdirs();<br>                if (!dirsCreated) {<br>                    throw new RuntimeException(&quot;Failed to create output directory: &quot; + outputDir);<br>                }<br>            }<br><br>            // Output the class to a file<br>            String fileName = outputDir + &quot;/&quot; + className + &quot;.java&quot;;<br>            try (FileWriter writer = new FileWriter(fileName)) {<br>                writer.write(classBuilder.toString());<br>            }<br><br>            System.out.println(&quot;Entity class generated at: &quot; + fileName);<br><br>        } catch (Exception e) {<br>            System.err.println(&quot;Error generating entity class: &quot; + e.getMessage());<br>            e.printStackTrace();<br>        }<br>    }<br><br>    private String mapToJavaType(String sqlType) {<br>        switch (sqlType.toUpperCase()) {<br>            case &quot;VARCHAR&quot;:<br>            case &quot;CHAR&quot;:<br>            case &quot;TEXT&quot;:<br>                return &quot;String&quot;;<br>            case &quot;INT4&quot;:<br>            case &quot;INT&quot;:<br>            case &quot;INT2&quot;:<br>            case &quot;INT8&quot;:<br>            case &quot;INTEGER&quot;:<br>                return &quot;Integer&quot;;<br>            case &quot;BIGINT&quot;:<br>                return &quot;Long&quot;;<br>            case &quot;FLOAT&quot;:<br>            case &quot;REAL&quot;:<br>            case &quot;DOUBLE&quot;:<br>            case &quot;DECIMAL&quot;:<br>                return &quot;Double&quot;;<br>            case &quot;DATE&quot;:<br>                return &quot;java.time.LocalDate&quot;;<br>            case &quot;TIMESTAMP&quot;:<br>            case &quot;DATETIME&quot;:<br>                return &quot;java.time.LocalDateTime&quot;;<br>            case &quot;TIMESTAMPTZ&quot;:<br>                return &quot;Timestamp&quot;;<br>            case &quot;BOOLEAN&quot;:<br>                return &quot;Boolean&quot;;<br>            case &quot;BLOB&quot;:<br>            case &quot;BYTEA&quot;:<br>                return &quot;byte[]&quot;;<br>            default:<br>                return &quot;Object&quot;; // Default fallback<br>        }<br>    }<br><br>    private String capitalize(String str) {<br>        String[] parts = str.split(&quot;_&quot;);<br>        StringBuilder className = new StringBuilder();<br><br>        for (String part : parts) {<br>            className.append(part.substring(0, 1).toUpperCase())<br>                    .append(part.substring(1).toLowerCase());<br>        }<br><br>        return className.toString();<br>    }<br><br>    private String toCamelCase(String str) {<br>        // Split by underscore (_)<br>        String[] parts = str.split(&quot;_&quot;);<br>        StringBuilder camelCaseString = new StringBuilder(parts[0].toLowerCase());<br><br>        // Capitalize the first letter of each subsequent part and append to the result<br>        for (int i = 1; i &lt; parts.length; i++) {<br>            camelCaseString.append(parts[i].substring(0, 1).toUpperCase())<br>                    .append(parts[i].substring(1).toLowerCase());<br>        }<br><br>        return camelCaseString.toString();<br>    }<br><br>}</pre><h3>Benefits of Automation: Why Developers Should Adopt This Approach</h3><h4>1. Improved Productivity</h4><p>Automating bean generation significantly reduces the time required to create entity classes, allowing developers to focus on more critical tasks like business logic and optimization.</p><h4>2. Error Prevention</h4><p>By automating repetitive and error-prone tasks, developers avoid common pitfalls such as incorrect type mappings and inconsistent naming conventions.</p><h4>3. Enhanced Code Quality</h4><p>The generated code is consistent, clean, and adheres to best practices, making it easier to read, maintain, and extend.</p><h4>4. Ease of Onboarding</h4><p>New team members can quickly generate entity classes without needing an in-depth understanding of the database schema, reducing the learning curve.</p><h4>5. Future-Proofing</h4><p>The tool can be extended to support new types or frameworks, ensuring long-term utility as the project evolves.</p><h3>Conclusion</h3><p>By automating entity class creation, developers can overcome the challenges of manual bean creation and improve overall productivity. The provided EntityGenerator class is a practical tool that simplifies this process, ensuring consistency, accuracy, and speed. This automation is not just a convenience—it’s a game-changer for modern Java development.</p><h3>If You Found This Useful…</h3><p>If you found this article insightful and the approach beneficial, don’t forget to <strong>like</strong>, <strong>comment</strong>, and <strong>clap</strong> for this article. It encourages me to bring more content like this to help developers.<br>Also, consider <strong>following me</strong> for more articles on simplifying Java development and tackling real-world challenges. Happy coding! 😊</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f7a922924a50" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[A Comprehensive Guide to @PathVariable and @RequestParam in Spring Boot: When to Use Each]]></title>
            <link>https://medium.com/@Mohd_Aamir_17/a-comprehensive-guide-to-pathvariable-and-requestparam-in-spring-boot-when-to-use-each-5dec54b314b5?source=rss-e48f7cb59ea8------2</link>
            <guid isPermaLink="false">https://medium.com/p/5dec54b314b5</guid>
            <category><![CDATA[optimization]]></category>
            <category><![CDATA[development]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[spring]]></category>
            <category><![CDATA[spring-boot]]></category>
            <dc:creator><![CDATA[Mohd Aamir ]]></dc:creator>
            <pubDate>Mon, 11 Nov 2024 17:24:28 GMT</pubDate>
            <atom:updated>2024-11-11T17:24:28.768Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VBYLgfmQVQGP-GmHxLDqFQ.jpeg" /></figure><h3>Introduction</h3><p>In RESTful API development with Spring Boot, passing parameters in URLs is essential to retrieve, filter, or manipulate data. Spring Boot provides two primary annotations, @PathVariable and @RequestParam, for capturing these parameters, each suited for different parts of the URL. This guide will explore the differences, best use cases, and how to choose between them to create effective APIs, as well as how to handle multiple @PathVariable instances in a single endpoint.</p><h3>1. Understanding URL Parameters in REST APIs</h3><p>RESTful APIs often need parameters to specify resources or control responses. These parameters can appear in:</p><ul><li><strong>Path variables</strong> as part of the URL path itself, like /employees/123.</li><li><strong>Query parameters</strong> after a ? in the URL, like /employees?department=HR.</li></ul><p>Each serves a specific purpose:</p><ul><li><strong>Path variables</strong> typically identify specific resources.</li><li><strong>Query parameters</strong> usually modify or filter results, such as by sorting or pagination.</li></ul><h3>2. What is @PathVariable?</h3><ul><li><strong>Definition</strong>: @PathVariable binds a method parameter to a URI template variable.</li><li><strong>Use Case</strong>: Use @PathVariable when the value forms part of the URL path and uniquely identifies a resource.</li></ul><p><strong>Example</strong>:</p><pre>@GetMapping(&quot;/employees/{id}&quot;)<br>public ResponseEntity&lt;Employee&gt; getEmployeeById(@PathVariable(&quot;id&quot;) Long employeeId) {<br>    return ResponseEntity.ok(employeeService.getEmployeeById(employeeId));<br>}</pre><p><strong>Explanation</strong>:</p><ul><li>{id} in the URL path is a placeholder, captured by @PathVariable(&quot;id&quot;).</li><li>Accessing /employees/123 binds 123 to employeeId.</li><li>Ideal for targeting specific resources (e.g., /users/{userId}, /products/{productId}).</li></ul><h3>3. What is @RequestParam?</h3><ul><li><strong>Definition</strong>: @RequestParam binds a method parameter to a query parameter in the URL.</li><li><strong>Use Case</strong>: Use @RequestParam when data is optional or modifies the behavior of the request without changing the core path.</li></ul><p><strong>Example</strong>:</p><pre>@GetMapping(&quot;/employees&quot;)<br>public ResponseEntity&lt;List&lt;Employee&gt;&gt; getEmployees(@RequestParam(name = &quot;department&quot;, required = false) String department) {<br>    return ResponseEntity.ok(employeeService.getEmployeesByDepartment(department));<br>}</pre><p><strong>Explanation</strong>:</p><ul><li>Here, department is passed as a query parameter, e.g., /employees?department=HR.</li><li>Commonly used for filters, sorts, and pagination.</li></ul><p>4. Key Differences Between @PathVariable and @RequestParam</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/570/1*l0pWa_f77pKDDYf1-FvG0Q.png" /></figure><h3>5. When to Use @PathVariable</h3><ul><li><strong>Best for identifying specific resources</strong>: Use @PathVariable when the parameter uniquely identifies a resource in the system.</li><li><strong>Example Use Cases</strong>:</li><li>Accessing a user by ID: /users/{userId}</li><li>Viewing a product by ID: /products/{productId}</li><li>Retrieving an order by order number: /orders/{orderNumber}</li></ul><p><strong>Code Example</strong>:</p><pre>@GetMapping(&quot;/products/{productId}&quot;)<br>public ResponseEntity&lt;Product&gt; getProductById(@PathVariable Long productId) {<br>    return ResponseEntity.ok(productService.getProductById(productId));<br>}</pre><h3>6. When to Use @RequestParam</h3><ul><li><strong>Ideal for optional data</strong>: Use @RequestParam for parameters that adjust the results, without changing the resource being accessed.</li><li><strong>Example Use Cases</strong>:</li><li>Filtering, e.g., /products?category=electronics</li><li>Pagination, e.g., /employees?page=2&amp;size=10</li><li>Sorting, e.g., /products?sort=price,desc</li></ul><p><strong>Code Example</strong>:</p><pre>@GetMapping(&quot;/products&quot;)<br>public ResponseEntity&lt;List&lt;Product&gt;&gt; getProducts(@RequestParam(required = false) String category) {<br>    return ResponseEntity.ok(productService.getProductsByCategory(category));<br>}</pre><h3>7. Handling Multiple @PathVariable Annotations</h3><p>Sometimes, an endpoint may need to capture multiple path variables. Spring Boot supports this by allowing you to define multiple @PathVariable annotations within a single method.</p><h4>Example with Multiple Path Variables</h4><p>Suppose you need to delete a department by its id and appId:</p><pre>@DeleteMapping(&quot;/delete/{id}/{appId}&quot;)<br>public ResponseEntity&lt;Object&gt; deleteDepartment(<br>        @PathVariable Long id,<br>        @PathVariable Long appId) {<br><br>    userService.deleteDepartment(id, appId);<br>    return ResponseEntity.ok(&quot;Department deleted successfully&quot;);<br>}</pre><ul><li><strong>Explanation</strong>:</li><li>Each @PathVariable maps to a specific part of the URL.</li><li>The order in the method should match the URL path’s order.</li><li>For /delete/1/5, 1 is captured as id and 5 as appId.</li></ul><h4>Specifying Path Variable Names Explicitly</h4><p>You can explicitly specify the path variable name if the method parameter names differ:</p><pre>@DeleteMapping(&quot;/delete/{id}/{appId}&quot;)<br>public ResponseEntity&lt;Object&gt; deleteDepartment(<br>        @PathVariable(&quot;id&quot;) Long departmentId,<br>        @PathVariable(&quot;appId&quot;) Long applicationId) {<br><br>    userService.deleteDepartment(departmentId, applicationId);<br>    return ResponseEntity.ok(&quot;Department deleted successfully&quot;);<br>}</pre><p>Here, departmentId and applicationId differ from id and appId in the URL, so we explicitly match the names in @PathVariable.</p><h3>8. Combining @PathVariable and @RequestParam</h3><p>Sometimes, you need both @PathVariable and @RequestParam in the same endpoint. This can happen when accessing a specific resource but also needing additional filters or options.</p><p><strong>Code Example</strong>:</p><pre>@GetMapping(&quot;/employees/{id}&quot;)<br>public ResponseEntity&lt;Employee&gt; getEmployeeById(<br>        @PathVariable Long id,<br>        @RequestParam(name = &quot;includeDetails&quot;, required = false, defaultValue = &quot;false&quot;) boolean includeDetails) {<br><br>    Employee employee = employeeService.getEmployeeById(id, includeDetails);<br>    return ResponseEntity.ok(employee);<br>}</pre><p><strong>Explanation</strong>:</p><ul><li>id identifies the employee (a path variable).</li><li>includeDetails is a query parameter used to toggle extra information.</li></ul><h3>9. Converting Between @PathVariable and @RequestParam</h3><p>If you need to convert a @PathVariable to a @RequestParam (or vice versa), you’ll need to change both the endpoint and how it’s called.</p><h4>1. Converting @PathVariable to @RequestParam:</h4><pre>@GetMapping(&quot;/employees&quot;)<br>    public ResponseEntity&lt;Employee&gt; getEmployee(@RequestParam Long id) {<br>        // Logic using id<br>    }<br>// URL example: /employees?id=123</pre><p>2. Converting @RequestParam to @PathVariable:</p><pre>@GetMapping(&quot;/employees/{id}&quot;)<br>    public ResponseEntity&lt;Employee&gt; getEmployee(@PathVariable Long id) {<br>        // Logic using id<br>    }<br>// URL example: /employees/123</pre><h3>10. Error Handling and Validation with @PathVariable and @RequestParam</h3><p>For robust code:</p><ul><li><strong>@RequestParam(required = false)</strong>: Makes a query parameter optional.</li><li><strong>Setting Default Values</strong>: Provide defaults for query parameters as needed:</li></ul><pre>@RequestParam(defaultValue = &quot;10&quot;) int pageSize</pre><ul><li><strong>Error Handling</strong>: Implement custom error handling for missing or incorrect parameters to avoid runtime issues.</li></ul><h3>Conclusion</h3><p>Choosing between @PathVariable and @RequestParam depends on the parameter’s role in the URL:</p><ul><li>Use @PathVariable for identifying specific resources, including handling multiple identifiers in one endpoint.</li><li>Use @RequestParam for optional or filtering data.</li></ul><p>With this guide, you’ll be able to implement @PathVariable and @RequestParam effectively in Spring Boot, creating RESTful APIs that are clear, maintainable, and follow best practices.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5dec54b314b5" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Can You Use @JsonBackReference and @JsonIgnore on the Same Field in Java?]]></title>
            <link>https://medium.com/@Mohd_Aamir_17/can-you-use-jsonbackreference-and-jsonignore-on-the-same-field-in-java-fdf40f07faa1?source=rss-e48f7cb59ea8------2</link>
            <guid isPermaLink="false">https://medium.com/p/fdf40f07faa1</guid>
            <category><![CDATA[spring-boot]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[json]]></category>
            <category><![CDATA[development]]></category>
            <category><![CDATA[spring]]></category>
            <dc:creator><![CDATA[Mohd Aamir ]]></dc:creator>
            <pubDate>Tue, 05 Nov 2024 13:19:01 GMT</pubDate>
            <atom:updated>2024-11-05T13:19:01.479Z</atom:updated>
            <content:encoded><![CDATA[<p>In Java applications, especially when working with frameworks like Spring Boot and JPA, managing complex data relationships can sometimes lead to circular dependencies and infinite recursion issues during serialization. To handle these cases, developers often rely on annotations like @JsonBackReference and @JsonIgnore from the Jackson library. But what happens if you use both on the same field?</p><p>This article delves into the purpose of each annotation, when and why you might use each, and why combining them on the same field should be avoided.</p><h3>Understanding @JsonBackReference and @JsonIgnore</h3><p>To effectively use these annotations, it’s important to understand how each works:</p><h4>@JsonBackReference</h4><p>@JsonBackReference is part of the Jackson library’s managed references feature and is commonly used in <strong>bidirectional relationships</strong>. In these relationships, @JsonBackReference works in tandem with @JsonManagedReference:</p><ul><li><strong>Purpose</strong>: To handle parent-child relationships without causing infinite recursion during JSON serialization.</li><li><strong>Usage</strong>: Apply @JsonManagedReference on the parent field and @JsonBackReference on the child field.</li><li><strong>Behavior</strong>: When serializing, @JsonBackReference prevents the annotated field from being included in the JSON output. During deserialization, however, it can still populate the field, which allows for a bidirectional reference to be maintained.</li></ul><p>Example:</p><pre>@Entity<br>public class User {<br>    @Id<br>    private Long id;<br><br>    @JsonManagedReference<br>    @OneToMany(mappedBy = &quot;user&quot;)<br>    private List&lt;Order&gt; orders;<br>}<br><br>@Entity<br>public class Order {<br>    @Id<br>    private Long id;<br><br>    @JsonBackReference<br>    @ManyToOne<br>    @JoinColumn(name = &quot;user_id&quot;)<br>    private User user;<br>}</pre><p>In this case:</p><ul><li>The User class has a list of orders annotated with @JsonManagedReference, and the Order class has a reference back to User with @JsonBackReference.</li><li>This setup prevents infinite recursion when serializing a User object with associated Order objects.</li></ul><h4>@JsonIgnore</h4><p>@JsonIgnore is a straightforward annotation that tells Jackson to <strong>completely ignore a field</strong> during both serialization and deserialization. It’s helpful for fields that should not be included in the JSON output or input, regardless of any relationships.</p><p>Example:</p><pre>@Entity<br>public class Order {<br>    @Id<br>    private Long id;<br><br>    @JsonIgnore<br>    @ManyToOne<br>    @JoinColumn(name = &quot;user_id&quot;)<br>    private User user;<br>}</pre><p>In this case:</p><ul><li>When @JsonIgnore is applied to the user field in Order, it’s entirely omitted from any JSON representation of Order objects.</li><li>This approach is simpler and removes the reference to User altogether, which can be useful if the User information is not necessary in the JSON output.</li></ul><h3>Why Using Both @JsonBackReference and @JsonIgnore Together Can Cause Problems</h3><p>While you can technically apply both @JsonBackReference and @JsonIgnore on the same field, doing so often results in <strong>unpredictable behavior</strong>:</p><ol><li><strong>Contradictory Instructions</strong>: @JsonBackReference and @JsonIgnore have fundamentally different purposes.</li></ol><ul><li>@JsonBackReference expects a paired @JsonManagedReference to manage circular dependencies, allowing the reference to exist during deserialization while ignoring it during serialization.</li><li>@JsonIgnore completely removes the field from both serialization and deserialization.</li></ul><p>Applying both simultaneously sends conflicting instructions to Jackson, which may cause one annotation to override the other in unexpected ways.</p><p><strong>2. Impact on Serialization and Deserialization</strong>:</p><ul><li>If @JsonIgnore takes precedence, the field is removed from both serialization and deserialization processes, potentially breaking the managed relationship intended by @JsonBackReference.</li><li>If @JsonBackReference takes precedence, the field will still be ignored during serialization but will be populated during deserialization, possibly leading to inconsistent results if the field isn’t meant to be bidirectional.</li></ul><p><strong>3. Code Maintenance and Clarity</strong>:</p><ul><li>Adding both annotations complicates the code and may confuse other developers, who may be unsure of which behavior will actually apply.</li><li>The redundancy makes debugging more challenging, especially when trying to trace JSON processing issues.</li></ul><h3>Choosing Between @JsonBackReference and @JsonIgnore</h3><p>The best approach is to select the annotation that aligns with the relationship model you need. Here are some scenarios to guide your choice:</p><ol><li><strong>Bidirectional Relationships with Parent-Child References</strong>:</li></ol><ul><li>Use @JsonBackReference and @JsonManagedReference together.</li><li>Avoid using @JsonIgnore here, as @JsonBackReference already provides the desired behavior for JSON handling.</li></ul><p><strong>2. Unidirectional Relationships or Simpler Models</strong>:</p><ul><li>If you don’t need bidirectional navigation in JSON, @JsonIgnore alone is simpler and eliminates the field from both serialization and deserialization.</li><li>This is often sufficient for many cases and avoids potential confusion.</li></ul><p><strong>3. Hybrid Case (Edge Case)</strong>:</p><ul><li>In rare cases, if a field needs to be omitted only during serialization, but available for deserialization without a managed reference, @JsonIgnoreProperties can be an alternative approach for more control over JSON processing.</li></ul><h3>Conclusion: Avoiding Confusion and Ensuring Correct JSON Handling</h3><p>In summary, while @JsonBackReference and @JsonIgnore can technically be used together, doing so is generally not recommended. The best approach is to understand the unique role each annotation plays and select the one that fits the specific needs of your relationship model:</p><ul><li>Use @JsonBackReference and @JsonManagedReference together for bidirectional relationships.</li><li>Use @JsonIgnore when you need a field excluded from both serialization and deserialization.</li></ul><p>By choosing the right annotation for each scenario, you can ensure clean, maintainable code and predictable JSON processing behavior.</p><h3>Final Thoughts</h3><p>Using @JsonBackReference and @JsonIgnore annotations in Java is a powerful approach to handling JSON serialization, especially when managing complex relationships between entities. By choosing the right annotation for your needs, you can create cleaner, more maintainable code and avoid common pitfalls in serialization.</p><p>If you found this article informative and helpful, consider giving it a like and a share to help others discover the valuable insights into Java, Spring Boot, and advanced serialization techniques! 🤩 Following me will also keep you updated on my latest content, so you can stay ahead of the curve in the world of Java and Spring Boot development. Your support means a lot, and I appreciate your help in spreading the word! 😊</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fdf40f07faa1" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Mastering JSON in Java: A Comprehensive Guide to Handling JSON Objects, Arrays, and Nodes with…]]></title>
            <link>https://medium.com/@Mohd_Aamir_17/mastering-json-in-java-a-comprehensive-guide-to-handling-json-objects-arrays-and-nodes-with-df57bf0ebff1?source=rss-e48f7cb59ea8------2</link>
            <guid isPermaLink="false">https://medium.com/p/df57bf0ebff1</guid>
            <category><![CDATA[json]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[json-api]]></category>
            <category><![CDATA[spring-boot]]></category>
            <category><![CDATA[spring]]></category>
            <dc:creator><![CDATA[Mohd Aamir ]]></dc:creator>
            <pubDate>Mon, 04 Nov 2024 17:11:47 GMT</pubDate>
            <atom:updated>2024-11-04T17:11:47.872Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OlB8v33dZ11WASKw-pbOog.jpeg" /></figure><h3>Mastering JSON in Java: A Comprehensive Guide to Handling JSON Objects, Arrays, and Nodes with Jackson</h3><h3>Introduction</h3><p>JSON (JavaScript Object Notation) is an essential format for data exchange in modern web applications. Whether you’re developing REST APIs, handling data transformation, or integrating with third-party services, understanding how to handle JSON data efficiently in Java is crucial. This article offers an in-depth look at how to parse, create, and manipulate JSON objects, arrays, and nodes using the Jackson library, covering advanced scenarios to equip you with the tools to tackle complex JSON data in Java.</p><h3>1. Choosing Jackson for JSON Processing in Java</h3><p>While Java has several libraries for JSON handling — such as Gson, org.json, and JSON-P — <strong>Jackson</strong> stands out for its performance, extensive feature set, and flexibility. Jackson’s ObjectMapper, JsonNode, ObjectNode, and ArrayNode classes provide a robust way to work with JSON data dynamically or in a structured manner. Here, we’ll focus on leveraging these classes to handle JSON efficiently.</p><h3>2. Handling JSON Objects in Java</h3><p>A <strong>JSON Object</strong> is a collection of key-value pairs, similar to a Map in Java. Jackson&#39;s ObjectMapper can convert JSON strings into Java objects or JsonNode instances, giving you flexible access to JSON data without predefined classes.</p><h4>Example JSON Object</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/330/1*v92p5lRJJZyFGudaGa1R4w.png" /></figure><h4>Parsing JSON Objects</h4><p>Using Jackson’s ObjectMapper, you can convert JSON strings to JsonNode, a versatile data structure that represents JSON data as a tree.</p><pre>import com.fasterxml.jackson.databind.JsonNode;<br>import com.fasterxml.jackson.databind.ObjectMapper;<br><br>String jsonString = &quot;{\&quot;name\&quot;: \&quot;Alice\&quot;, \&quot;age\&quot;: 30, \&quot;address\&quot;: {\&quot;street\&quot;: \&quot;123 Maple Street\&quot;, \&quot;city\&quot;: \&quot;Wonderland\&quot;}, \&quot;isActive\&quot;: true}&quot;;<br>ObjectMapper objectMapper = new ObjectMapper();<br><br>JsonNode jsonObject = objectMapper.readTree(jsonString);<br>System.out.println(&quot;Name: &quot;+jsonObject.get(&quot;name&quot;).asText());<br>System.out.println(&quot;City: &quot;+jsonObject.get(&quot;address&quot;).get(&quot;city&quot;).asText());</pre><p>Here, we parse the JSON into a JsonNode object, which allows you to access nested fields (like address.city) using .get() methods. Jackson’s JsonNode is dynamic, so it handles missing or optional fields gracefully.</p><h4>Creating JSON Objects Dynamically</h4><p>If you need to construct JSON objects on the fly, Jackson’s ObjectNode class is ideal.</p><pre>import com.fasterxml.jackson.databind.node.ObjectNode;<br><br>ObjectNode jsonObject = objectMapper.createObjectNode();<br>jsonObject.put(&quot;name&quot;, &quot;Alice&quot;);<br>jsonObject.put(&quot;age&quot;, 30);<br>jsonObject.set(&quot;address&quot;, objectMapper.createObjectNode().put(&quot;street&quot;, &quot;123 Maple Street&quot;).put(&quot;city&quot;, &quot;Wonderland&quot;));<br>jsonObject.put(&quot;isActive&quot;, true);<br><br>System.out.println(jsonObject.toString());</pre><p>With ObjectNode, you can easily add, modify, or remove fields, making it perfect for building JSON responses in REST APIs or handling data transformations.</p><h3>3. Working with JSON Arrays in Java</h3><p>A <strong>JSON Array</strong> is an ordered collection of values, which may be objects, strings, numbers, or other primitives.</p><h4>Example JSON Array</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/319/1*0Aj__gGAr9bsok4RTa4yKA.png" /></figure><h4>Parsing JSON Arrays with Jackson</h4><p>Jackson’s ArrayNode class, which extends JsonNode, is specifically for handling JSON arrays.</p><pre>String jsonArrayString = &quot;[{\&quot;id\&quot;: 1, \&quot;name\&quot;: \&quot;John\&quot;}, {\&quot;id\&quot;: 2, \&quot;name\&quot;: \&quot;Jane\&quot;}]&quot;;<br>ArrayNode jsonArray = (ArrayNode) objectMapper.readTree(jsonArrayString);<br><br>for (JsonNode element : jsonArray) {<br>    System.out.println(&quot;ID: &quot; + element.get(&quot;id&quot;).asInt());<br>    System.out.println(&quot;Name: &quot; + element.get(&quot;name&quot;).asText());<br>}</pre><h4>Constructing JSON Arrays</h4><p>Use ArrayNode to dynamically build JSON arrays. This is especially useful when constructing complex JSON responses.</p><pre>ArrayNode jsonArray = objectMapper.createArrayNode();<br><br>ObjectNode person1 = objectMapper.createObjectNode().put(&quot;id&quot;, 1).put(&quot;name&quot;, &quot;Alice&quot;);<br>ObjectNode person2 = objectMapper.createObjectNode().put(&quot;id&quot;, 2).put(&quot;name&quot;, &quot;Bob&quot;);<br><br>jsonArray.add(person1);<br>jsonArray.add(person2);<br><br>System.out.println(jsonArray.toString());</pre><p>This flexibility allows you to dynamically add elements, useful in situations where the JSON array structure needs to be generated or modified at runtime.</p><h3>4. Understanding JsonNode: The Dynamic JSON Handler</h3><p>The <strong>JsonNode</strong> class is the most versatile part of Jackson for JSON handling. JsonNode can represent any JSON structure—whether an object, array, or primitive—and provides methods to traverse, query, and modify JSON data dynamically.</p><h4>Navigating Nested JSON Structures</h4><p>Consider the following complex JSON structure:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/474/1*CxDeQdy7j7QvlMu0OmnFhQ.png" /></figure><p>With JsonNode, you can easily traverse nested structures without needing a custom Java class:</p><pre>JsonNode rootNode = objectMapper.readTree(complexJsonString);<br>JsonNode contacts = rootNode.path(&quot;person&quot;).path(&quot;contacts&quot;);<br><br>for (JsonNode contact : contacts) {<br>    System.out.println(&quot;Contact Type: &quot; + contact.get(&quot;type&quot;).asText());<br>    System.out.println(&quot;Contact Value: &quot; + contact.get(&quot;value&quot;).asText());<br>}</pre><p>This flexibility is invaluable when working with data structures that may change over time, as JsonNode allows you to access any field without predefined mappings.</p><h3>5. Choosing Between JsonArray and JsonNode</h3><p>When working with JSON data, understanding when to use ArrayNode (Jackson’s JSON array representation) versus JsonNode can lead to cleaner, more maintainable code:</p><ul><li><strong>Use </strong><strong>ArrayNode when</strong>:</li><li>You are working with a fixed structure where you know the data is an array.</li><li>You need to perform operations specifically on array elements, such as filtering, sorting, or mapping.</li><li><strong>Use </strong><strong>JsonNode when</strong>:</li><li>You are dealing with dynamic or nested structures, where some fields may be arrays, while others are objects or primitives.</li><li>You need a flexible approach to handle JSON without strict adherence to a particular structure.</li></ul><p>In essence, ArrayNode is suitable for structured JSON arrays, while JsonNode is ideal for complex, dynamic JSON processing.</p><h3>6. Converting JSON to Java Objects and Vice Versa</h3><p>One of Jackson’s strongest features is its ability to easily convert JSON data into Java objects, and vice versa.</p><h4>JSON to Java Object</h4><p>Using ObjectMapper, you can map JSON directly to a Java class:</p><pre>class Person {<br>    public String name;<br>    public int age;<br>    public boolean isActive;<br>}<br><br>String jsonString = &quot;{\&quot;name\&quot;: \&quot;Alice\&quot;, \&quot;age\&quot;: 30, \&quot;isActive\&quot;: true}&quot;;<br>Person person = objectMapper.readValue(jsonString, Person.class);<br><br>System.out.println(&quot;Person&#39;s Name: &quot; + person.name);</pre><h4>Java Object to JSON</h4><p>You can also serialize a Java object into a JSON string using writeValueAsString():</p><pre>Person person = new Person();<br>person.name = &quot;Alice&quot;;<br>person.age = 30;<br>person.isActive = true;<br><br>String jsonOutput = objectMapper.writeValueAsString(person);<br>System.out.println(&quot;JSON Output: &quot; + jsonOutput);</pre><p>Using this approach provides type safety and simplifies working with JSON in structured scenarios.</p><h3>7. Advanced JSON Handling Techniques</h3><h4>Merging JSON Objects</h4><p>Merging JSON objects is useful for combining data from multiple sources. Jackson’s ObjectNode provides a way to merge objects:</p><pre>ObjectNode obj1 = objectMapper.createObjectNode().put(&quot;name&quot;, &quot;Alice&quot;);<br>ObjectNode obj2 = objectMapper.createObjectNode().put(&quot;age&quot;, 30);<br><br>obj1.setAll(obj2);  // Merges obj2 into obj1<br>System.out.println(obj1.toString());</pre><h4>Filtering JSON Arrays</h4><p>For large datasets, you may want to filter JSON arrays based on specific conditions.</p><pre>ArrayNode filteredArray = objectMapper.createArrayNode();<br>for (JsonNode person : jsonArray) {<br>    if (person.get(&quot;age&quot;).asInt() &gt; 25) {<br>        filteredArray.add(person);<br>    }<br>}<br>System.out.println(filteredArray.toString());</pre><h4>Manipulating JSON with Path Expressions</h4><p>Jackson’s JsonNode allows you to use .path() for retrieving nested data without worrying about nulls, which prevents NullPointerExceptions and keeps your code clean.</p><h3>Conclusion</h3><p>Handling JSON data in Java is much simpler with the Jackson library, which provides versatile classes like JsonNode, ObjectNode, and ArrayNode to work with various JSON structures. Knowing when to use JsonNode for dynamic data, ObjectNode for objects, and ArrayNode for arrays will make your code more readable, maintainable, and resilient. Whether you’re parsing, constructing, or modifying JSON, this guide should serve as a comprehensive resource for mastering JSON in Java with Jackson.</p><p>If you enjoyed this article, please <strong>follow</strong> and <strong>clap</strong> to support more content like this!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=df57bf0ebff1" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Understanding Spring Stereotype Annotations: Why Incorrect Usage Can Break Your Application]]></title>
            <link>https://medium.com/@Mohd_Aamir_17/understanding-spring-stereotype-annotations-why-incorrect-usage-can-break-your-application-f2c2fa537234?source=rss-e48f7cb59ea8------2</link>
            <guid isPermaLink="false">https://medium.com/p/f2c2fa537234</guid>
            <category><![CDATA[development]]></category>
            <category><![CDATA[backend-development]]></category>
            <category><![CDATA[spring-boot]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[spring]]></category>
            <dc:creator><![CDATA[Mohd Aamir ]]></dc:creator>
            <pubDate>Wed, 09 Oct 2024 09:11:26 GMT</pubDate>
            <atom:updated>2024-10-09T09:11:26.269Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/275/1*l2zg7omhSfnJzpp9zJ88hQ.jpeg" /></figure><p>In a typical multi-layered Spring Boot application, managing layers and ensuring proper communication between them is crucial. These layers, including <strong>Controller</strong>, <strong>Service</strong>, <strong>DAO</strong>, and <strong>Repository</strong>, are all tied together by Spring’s powerful bean management and dependency injection mechanisms</p><p>One of the core ways Spring identifies and manages beans is through <strong>stereotype annotations</strong> such as @Service, @Repository, @Controller, and @Component. These annotations play a vital role in correctly classifying components into their respective layers and making sure the application runs smoothly.</p><p>However, using these annotations incorrectly can lead to issues like <strong>bean definition conflicts</strong> or Spring failing to understand which component belongs to which layer. This article will focus on two real-world cases where improper annotation usage can either allow your application to run successfully or cause it to fail.</p><h3>Case 1: Using @Repository in the DAO and Repository Layers</h3><p>In this first case, we examine the situation where we correctly annotate both the <strong>DAO layer</strong> and the <strong>Repository layer</strong> using @Repository. Here is the setup:</p><h3>DAO Implementation Layer (daoImpl)</h3><pre>@Repository<br>public class ProductDaoImpl implements ProductDao {<br>    // Custom DAO methods<br>}</pre><h3><strong>Repository Layer</strong></h3><pre>@Repository<br>public interface ProductRepository extends JpaRepository&lt;Product, Long&gt; {<br><br>}</pre><h3>Why This Works:</h3><p>In this scenario, we have used @Repository on both:</p><ul><li><strong>The </strong><strong>ProductRepository</strong>: This interface extends JpaRepository, which provides built-in methods like save(), findById(), delete(), etc. Spring Data JPA automatically detects this interface as a bean because it’s annotated with @Repository (or implicitly considered a repository even without the annotation).</li><li><strong>The </strong><strong>ProductDaoImpl</strong>: This class is marked with @Repository, making it part of the persistence layer. It might contain custom database operations that the JpaRepository cannot handle.</li></ul><p>Spring manages these components correctly, allowing the project to run successfully. Here’s why:</p><ul><li><strong>Correct Usage of </strong><strong>@Repository:</strong> The @Repository annotation tells Spring that these components belong to the data access layer.</li><li><strong>Separation of Concerns:</strong> The DAO (daoImpl) and the Repository (JpaRepository) are distinct but complementary. The DAO could be used for more complex, custom queries, while the Repository handles basic CRUD operations.</li></ul><p>Thus, Spring knows how to manage and inject these beans where needed, resulting in a smooth application startup.</p><h3>Case 2: Using @Service in the DAO and Service Layers</h3><p>Now, let’s look at a scenario where the application fails to start. Here is the setup where both the <strong>DAO implementation layer</strong> and the <strong>Service implementation layer</strong> are incorrectly annotated with @Service:</p><h3>DAO Implementation Layer (daoImpl)</h3><pre>@Service<br>public class ProductDaoImpl implements ProductDao {<br>    // Custom DAO methods<br>}</pre><h3><strong>Service Implementation Layer (</strong><strong>serviceImpl)</strong></h3><pre>@Service<br>public class ProductServiceImpl implements ProductService {<br>    // Business logic<br>}</pre><h3>Why This Fails:</h3><p>In this scenario, the project fails with an error when starting up. Let’s explore the reasons:</p><ul><li><strong>Incorrect Annotation on the DAO Layer:</strong> The ProductDaoImpl class is marked with @Service instead of @Repository. While @Service tells Spring that this class is part of the business logic layer, this class should actually be part of the <strong>data access layer</strong>, which requires the @Repository annotation.</li><li><strong>Bean Conflict:</strong> Since Spring is now managing both the ProductDaoImpl and ProductServiceImpl classes as service components (due to the @Service annotation on both), it can’t distinguish between them. This can lead to <strong>bean definition conflicts</strong> or <strong>incorrect bean injection</strong>.</li><li><strong>Misleading Role Assignment:</strong> The DAO layer is responsible for interacting with the database, and Spring uses @Repository to manage it. By marking the DAO class with @Service, you’re incorrectly assigning it the role of business logic, which creates confusion for Spring during dependency injection.</li></ul><h3>Error Example:</h3><pre>org.springframework.beans.factory.BeanDefinitionStoreException: I/O failure while processing configuration class [null]<br>at org.springframework.context.annotation.ConfigurationClassParser.processConfigurationClass(ConfigurationClassParser.java:251) ~[spring-context-6.1.2.jar:6.1.2]</pre><p>This type of error is typical when Spring is unable to correctly configure and manage your beans due to incorrect annotations or conflicts.</p><h3>Understanding the Proper Use of Annotations</h3><p>The difference between these two cases boils down to the <strong>correct use of annotations</strong>. Here’s a quick guide to help avoid such issues in the future:</p><h3>1. @Repository</h3><ul><li><strong>Use it in the Data Access Layer</strong> (DAO).</li><li>It tells Spring that the class is responsible for interacting with the database.</li><li>@Repository also provides exception translation from database-specific exceptions to Spring’s DataAccessException.</li></ul><h3>2. @Service</h3><ul><li><strong>Use it in the Business Logic Layer</strong> (Service).</li><li>It tells Spring that the class contains business logic and should be managed as part of the service layer.</li></ul><h3>3. @Component</h3><ul><li>This is a more generic annotation that can be used to mark any Spring-managed bean. However, it’s usually better to use more specific annotations like @Service, @Repository, or @Controller to make the role of the component clearer.</li></ul><h3>Correcting the Second Case:</h3><p>To fix the second case where the project fails to start, you need to ensure that each class is annotated correctly for its role:</p><h3>Corrected DAO Layer</h3><pre>@Repository<br>public class ProductDaoImpl implements ProductDao {<br>    // Custom DAO methods<br>}</pre><ul><li>The @Repository annotation tells Spring this is part of the data access layer and responsible for database interactions.</li></ul><h3>Corrected Service Layer</h3><pre>@Service<br>public class ProductServiceImpl implements ProductService {<br>    // Business logic<br>}</pre><blockquote>The @Service annotation correctly categorizes this class as a part of the business logic layer.</blockquote><h3>Key Takeaways</h3><ul><li><strong>Annotations Have Specific Roles:</strong> Using the correct annotations for each layer ensures that Spring understands the role of each component and manages it accordingly.</li><li><strong>Avoid Misuse of Annotations:</strong> Applying @Service to a DAO class, or @Repository to a service class, can confuse Spring’s bean management and lead to runtime errors or misconfigured components.</li><li><strong>Separation of Concerns:</strong> Always maintain a clean separation between the service, repository, and DAO layers. Each layer should handle a distinct responsibility: service for business logic, DAO for data access, and repository for CRUD operations.</li></ul><p>By understanding and applying the correct annotations, you can ensure that Spring manages your beans properly, avoids conflicts, and keeps your project running smoothly. Proper use of annotations not only improves the maintainability of your project but also prevents errors like the ones we saw in the second case.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f2c2fa537234" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>