<?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 Gokulnaths S on Medium]]></title>
        <description><![CDATA[Stories by Gokulnaths S on Medium]]></description>
        <link>https://medium.com/@gokulnaths.tech?source=rss-f795c82916bd------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*Pq68b9BeZX8QKcsoOo6WIw.jpeg</url>
            <title>Stories by Gokulnaths S on Medium</title>
            <link>https://medium.com/@gokulnaths.tech?source=rss-f795c82916bd------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 06 Dec 2026 08:57:17 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@gokulnaths.tech/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[ Spring Boot Search API — One Endpoint to Rule Them All]]></title>
            <link>https://medium.com/@gokulnaths.tech/spring-boot-search-api-one-endpoint-to-rule-them-all-978da4ae8102?source=rss-f795c82916bd------2</link>
            <guid isPermaLink="false">https://medium.com/p/978da4ae8102</guid>
            <category><![CDATA[java]]></category>
            <category><![CDATA[spring-boot]]></category>
            <category><![CDATA[rest-api]]></category>
            <dc:creator><![CDATA[Gokulnaths S]]></dc:creator>
            <pubDate>Fri, 30 May 2025 16:09:26 GMT</pubDate>
            <atom:updated>2025-05-30T16:31:33.065Z</atom:updated>
            <content:encoded><![CDATA[<h3>🌱 Spring Boot Search API — One Endpoint to Rule Them All</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jeRnHg5rWfqS_8iXkZHSsg.png" /></figure><p>If you’ve been working with Spring Boot for any amount of time, you’re probably well-versed in the holy trinity: @Controller, @Service, and @Repository. Each new entity in your project likely gets its own controller for CRUD operations and other business logic—at least for synchronous operations.</p><p>Creating POST, PUT, and DELETE endpoints is straightforward: just wire up your validations and business logic, and you&#39;re good to go.</p><p>But what about GET?</p><p>Let’s consider a simple Employee entity:</p><pre>public class Employee extends BaseUUIDEntity {<br>    private Long id;<br>    private String name;<br>    private String email;<br>    private String mobile;<br>    private String role;<br>    private String status;<br>    private String address;<br>}</pre><p>Now let’s say we need to fetch all employees with a given status. Easy!</p><pre>@GetMapping<br>public List&lt;Employee&gt; getEmployeesByStatus(@RequestParam String status) {<br>    return employeeRepository.findByStatus(status);<br>}</pre><p>Clean and simple, right? ✅</p><p>We close the ticket, push the code, and move on. But then comes a new requirement:</p><blockquote><em>“Can the API also filter by role?”</em></blockquote><p>Sure. Let’s update it:</p><pre>@GetMapping<br>public List&lt;Employee&gt; getEmployeesByStatusAndRole(@RequestParam String status,<br>                                                  @RequestParam String role) {<br>    return employeeRepository.findByStatusAndRole(status, role);<br>}</pre><p>Another deployment, another version bump.</p><p>Then another stakeholder chimes in:</p><blockquote><em>“We’d like to query by either </em><em>status or </em><em>role. Oh, and can we filter by </em><em>department too?”</em></blockquote><p>Uh-oh. Now we’re seeing the problem: too many combinations, too much maintenance.</p><h3>🛡️ Enter: Spring Data Specifications</h3><p>Spring Specifications offer a dynamic, reusable way to define queries using the JPA Criteria API.</p><p>Think of Specification&lt;T&gt; as a Predicate builder that gives you fine-grained control over what you query—at runtime.</p><p>Let’s build a flexible query parser using Specification&lt;T&gt;.</p><h3>🔧 Dynamic Search Builder</h3><pre>public &lt;T&gt; Specification&lt;T&gt; parseSearchParams(MultiValueMap&lt;String, String&gt; params) {<br>    return (root, query, criteriaBuilder) -&gt; {<br>        List&lt;Predicate&gt; predicates = new ArrayList&lt;&gt;();<br>        for (Map.Entry&lt;String, List&lt;String&gt;&gt; param : params.entrySet()) {<br>            String key = param.getKey();<br>            List&lt;String&gt; values = param.getValue();<br>            if (key.equals(&quot;page&quot;) || key.equals(&quot;size&quot;) || key.equals(&quot;sort&quot;)) {<br>                continue; // skip pagination/sorting params<br>            }<br>            try {<br>                Path&lt;?&gt; path = root.get(key);<br>                if (values.get(0).startsWith(&quot;in:&quot;)) {<br>                    String[] valuesArray = values.get(0).substring(3).split(&quot;,&quot;);<br>                    List&lt;String&gt; trimmedValues = Arrays.stream(valuesArray)<br>                            .map(String::trim)<br>                            .collect(Collectors.toList());<br>                    predicates.add(path.in(trimmedValues));<br>                    continue;<br>                }<br>                for (String value : values) {<br>                    if (value.startsWith(&quot;eq:&quot;)) {<br>                        predicates.add(criteriaBuilder.equal(path, value.substring(3)));<br>                    } else if (value.startsWith(&quot;like:&quot;)) {<br>                        predicates.add(criteriaBuilder.like(path.as(String.class), &quot;%&quot; + value.substring(5) + &quot;%&quot;));<br>                    } else if (value.startsWith(&quot;gt:&quot;)) {<br>                        predicates.add(criteriaBuilder.greaterThan(path.as(String.class), value.substring(3)));<br>                    } else if (value.startsWith(&quot;gte:&quot;)) {<br>                        predicates.add(criteriaBuilder.greaterThanOrEqualTo(path.as(String.class), value.substring(4)));<br>                    } else if (value.startsWith(&quot;lt:&quot;)) {<br>                        predicates.add(criteriaBuilder.lessThan(path.as(String.class), value.substring(3)));<br>                    } else if (value.startsWith(&quot;lte:&quot;)) {<br>                        predicates.add(criteriaBuilder.lessThanOrEqualTo(path.as(String.class), value.substring(4)));<br>                    }<br>                }<br>            } catch (Exception e) {<br>                log.error(&quot;Error creating predicate for {}:{}&quot;, key, values, e);<br>            }<br>        }<br>        return predicates.isEmpty()<br>                ? criteriaBuilder.conjunction()<br>                : criteriaBuilder.and(predicates.toArray(new Predicate[0]));<br>    };<br>}</pre><h3>✅ Final API Endpoint</h3><pre>@GetMapping<br>public List&lt;Employee&gt; getEmployees(@RequestParam MultiValueMap&lt;String, String&gt; params) {<br>    Specification&lt;Employee&gt; spec = parseSearchParams(params);<br>    return employeeRepository.findAll(spec);<br>}</pre><h3>📦 Sample Queries</h3><p>Now this one endpoint supports all these use cases:</p><pre># Find all active employees<br>curl -X GET &quot;http://localhost:8080/api/employees?status=eq:ACTIVE&quot;<br><br># Find all active employees with &#39;manager&#39; in role<br>curl -X GET &quot;http://localhost:8080/api/employees?status=eq:ACTIVE&amp;role=like:manager&quot;<br><br># Find employees in specific roles<br>curl -X GET &quot;http://localhost:8080/api/employees?role=in:Manager,Engineer&quot;</pre><h3>🎯 Why This Matters</h3><ul><li><strong>No new endpoints</strong> for every filter combo.</li><li><strong>No need to extend repository interfaces</strong> for every new search field.</li><li><strong>No redeployments</strong> for simple filter logic.</li><li><strong>Business-friendly and extensible</strong>.</li></ul><p>This pattern can be easily adapted for any entity, offering consistency and maintainability across your codebase.</p><blockquote><em>One endpoint, infinite queries. If there’s no business logic, this is </em>the way<em>.</em></blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=978da4ae8102" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>