<?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 Baris Eroglu  on Medium]]></title>
        <description><![CDATA[Stories by Baris Eroglu  on Medium]]></description>
        <link>https://medium.com/@baris.eroglu.03?source=rss-44d46b3439b8------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*t2wpNThQ0RXpZwU9STo4Dg.jpeg</url>
            <title>Stories by Baris Eroglu  on Medium</title>
            <link>https://medium.com/@baris.eroglu.03?source=rss-44d46b3439b8------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Wed, 02 Dec 2026 02:23:44 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@baris.eroglu.03/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[Query Service with Spring Data Specification And Factory Design Pattern]]></title>
            <link>https://medium.com/kocfinanstech/query-service-with-spring-data-specification-and-factory-design-pattern-c7059c8ff27c?source=rss-44d46b3439b8------2</link>
            <guid isPermaLink="false">https://medium.com/p/c7059c8ff27c</guid>
            <category><![CDATA[spring-boot]]></category>
            <category><![CDATA[factory-pattern]]></category>
            <category><![CDATA[dynamic-query]]></category>
            <category><![CDATA[spring-data]]></category>
            <category><![CDATA[specifications]]></category>
            <dc:creator><![CDATA[Baris Eroglu ]]></dc:creator>
            <pubDate>Sat, 24 Jun 2023 21:22:22 GMT</pubDate>
            <atom:updated>2023-06-29T18:36:52.260Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Qp_TmPYzInW4gixIrdv5zw.png" /></figure><h3>Introduction</h3><p>In big software architectures, mostly there are huge tables which stores important data and usually more than one applications connect and execute database queries to communicate with it. Since several projects connect to the same table, this creates code duplications (entity, repository classes etc.) in different applications. When we think about huge tables with hundreds of columns, those duplications become a nightmare.</p><p>In this article, I will try to give you an alternate solution for this problem and we will be doing that with a <strong><em>db-query-service</em></strong>.</p><h3>Service Architecture</h3><p>The name of the service (db-query-service) indicates that we will be executing different and complicated database queries. It will be a restful API using Spring Boot with Spring Data Specification.</p><h3>Spring Data Specification vs Spring Data JPA</h3><p>If you used Spring Boot before, you probably used Spring Data JPA to execute database queries. It is really simple and fast to learn. You just create a repository class and write some methods to create database queries.</p><pre>interface PlayerRepository extends JpaRepository&lt;Player, Long&gt; {<br>  <br>  List&lt;Player&gt; findAll();<br><br>  List&lt;Player&gt; findAllByNameLike(String name);<br><br>}</pre><p>However, it becomes a nightmare for developers when it comes to read complicated queries like this:</p><pre>interface PlayerRepository extends JpaRepository&lt;Player, Long&gt; {<br><br>  List&lt;Player&gt; findByNameStartingWithAndSurnameLikeAndAgeAndHeightGreaterThanAndTeamIn(String name,<br>                                                                                       String surname,<br>                                                                                       int age,<br>                                                                                       double height,<br>                                                                                       List&lt;String&gt; teams);<br>}</pre><p>We can simplify the query execution process with specifications and make them more flexible.</p><p>When using Spring Data Specifications, we create every part of the query one by one. For example, to query an attribute with “<strong><em>like”</em></strong> , we can create a method like:</p><pre>Specification&lt;Product&gt; nameLike = <br>      (root, query, criteriaBuilder) -&gt; <br>         criteriaBuilder.like(root.get(Product_.NAME), &quot;%&quot;+name+&quot;%&quot;);</pre><p>Specification strategy makes it flexible to create complicated queries, because we can define each criteria separately and combine them as we want. (For further readings about Spring Data Specifications, you can visit the <a href="https://reflectoring.io/spring-data-specifications/">Spring Data Specification Reading</a>.)</p><h3>Creating db-query-service</h3><p>Firstly, I want to show you the entity we are working on. This entity has the information of some NBA players.</p><pre>@Getter<br>@NoArgsConstructor<br>@Entity<br>public class Player {<br><br>    @Id<br>    @GeneratedValue(strategy = GenerationType.IDENTITY)<br>    private long id;<br>    private String name;<br>    private String surname;<br>    private String team;<br>    private int age;<br>    private double height;<br>    private int weight;<br>}</pre><p>In our service, we aim to generate complex db-queries for the Player entity from a json request like:</p><pre>{<br>    &quot;filterList&quot;: [<br>        {<br>            &quot;name&quot;: &quot;team&quot;,<br>            &quot;value&quot;: &quot;Celtics&quot;,<br>            &quot;operation&quot;: &quot;EQUALS&quot;<br>        }<br>    ]<br>}</pre><ul><li>“name” attribute indicates the column name.</li><li>“value” attribute will be the value to associate with column</li><li>“operation” will be the association type like equals, greater, less, in, like etc.</li></ul><p>For the definition of operations, we will be using the following enum class. These are the first operations that come to mind when writing select SQL queries.</p><pre>@AllArgsConstructor<br>@Getter<br>public enum OperationType {<br><br>    CONTAINS(ContainsCriteria.class),<br>    NOT_CONTAIN(NotContainsCriteria.class),<br>    EQUALS(EqualsCriteria.class),<br>    NOT_EQUAL(NotEqualsCriteria.class),<br>    BEGINS_WITH(BeginsWithCriteria.class),<br>    NOT_BEGIN_WITH(NotBeginsWithCriteria.class),<br>    ENDS_WITH(EndsWithCriteria.class),<br>    NOT_ENDS_WITH(NotEndsWithCriteria.class),<br>    NULL(NullCriteria.class),<br>    NOT_NULL(NotNullCriteria.class),<br>    GREATER_THAN(GreaterCriteria.class),<br>    GREATER_THAN_EQUAL(GreaterEqualsCriteria.class),<br>    LESS_THAN(LessCriteria.class),<br>    LESS_THAN_EQUAL(LessEqualCriteria.class),<br>    AFTER(AfterCriteria.class),<br>    BEFORE(BeforeCriteria.class);<br><br>    private final Class&lt;?&gt; criteria;<br>}</pre><p>You will see a criteria parameter for enum class. This is the connection between criteria and operation names. For every SQL operation, there is a criteria method to execute and those methods are in criteria classes. For example here is the ContainsCriteria class:</p><pre>public class ContainsCriteria extends Criteria {<br><br>    @Override<br>    public Predicate build(CriteriaModel model) {<br>        return model.cb().like(<br>                model.root().get(model.filterInfo().getName()),<br>                &quot;%&quot; + model.filterInfo().getValue() + &quot;%&quot;<br>        );<br>    }<br>}</pre><p>We have a Criteria model which simplifies the method parameters. It has criteria builder and root objects to define criteria and FilterInfo object to access requested values. Here is the CriteriaModel record.</p><pre>public record CriteriaModel(CriteriaBuilder cb,<br>                             Root&lt;?&gt; root,<br>                             FilterInfo filterInfo) {<br>                            <br>}</pre><p>Since our solution is to create dynamic SQL operations, we are using a creational design pattern: <strong><em>Factory Design Pattern</em></strong>. OperationType enum class has the information that which operation type will be created due to the requested operation. To use that information and create the criteria classes, we are going to create a factory class like:</p><pre>@Override<br>public Criteria createCriteria(OperationType operationType) {<br>    Class&lt;?&gt; criteriaClass = operationType.getCriteria();<br><br>    return (Criteria) criteriaClass.getConstructor().newInstance();<br>}</pre><p>Factory pattern is successful and we create the operations now. (If you want to learn a bit more about Factory Pattern you can visit the <a href="https://refactoring.guru/design-patterns/factory-method">link</a>) Then, we are going to create the Specification class which will be executing created criteria methods and returns to the service layer. (We are still in the repository layer if we think about the project architecture)</p><pre>@AllArgsConstructor<br>public class PlayerSpecification implements Specification&lt;Player&gt; {<br><br>    private final FilterInfo filterInfo;<br><br>    @Override<br>    public Predicate toPredicate(@NonNull Root&lt;Player&gt; root, @NonNull CriteriaQuery&lt;?&gt; query, @NonNull CriteriaBuilder criteriaBuilder) {<br><br>        try {<br>            Criteria criteria = new PlayerCriteriaFactory().createCriteria(filterInfo.getOperation());<br>            return criteria.build(new CriteriaModel(criteriaBuilder, root, filterInfo));<br>        } catch ( Exception e ) {<br>            throw new CriteriaBuildException(filterInfo);<br>        }<br>    }<br>}</pre><p>Finally here it is, the service layer. It obtains the request, then dynamically creates specifications and combine them. As you can see, operations combined with <strong><em>“and”</em></strong> operator. Maybe it can be made dynamic due to the request as well, but we are not going to do that in this article 😂.</p><p>In the last step, PlayerRepository executes the findAll method to find all those created specifications.</p><pre>@AllArgsConstructor<br>public class PlayerSpecification implements Specification&lt;Player&gt; {<br><br>    private final FilterInfo filterInfo;<br><br>    @Override<br>    public Predicate toPredicate(@NonNull Root&lt;Player&gt; root, @NonNull CriteriaQuery&lt;?&gt; query, @NonNull CriteriaBuilder criteriaBuilder) {<br><br>        try {<br>            Criteria criteria = new PlayerCriteriaFactory().createCriteria(filterInfo.getOperation());<br>            return criteria.build(new CriteriaModel(criteriaBuilder, root, filterInfo));<br>        } catch ( Exception e ) {<br>            throw new CriteriaBuildException(filterInfo);<br>        }<br>    }<br>}</pre><pre>public interface PlayerRepository extends JpaRepository&lt;Player, Long&gt;, JpaSpecificationExecutor&lt;Player&gt; {<br>}</pre><p>Now let’s do some testing.</p><h3>Tests</h3><p>I created a docker container to start a PostgreSQL database and created a table which includes some information about the NBA players.</p><p>When we want to find NBA Players which are older than 25, the JSON request should be like this:</p><pre>{<br>    &quot;filterList&quot;: [<br>        {<br>            &quot;name&quot;: &quot;age&quot;,<br>            &quot;value&quot;: 25,<br>            &quot;operation&quot;: &quot;GREATER_THAN&quot;<br>        }<br>    ]<br>}</pre><p>The result:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6ofK4ylWRoebXDFXJhy8Fw.png" /></figure><p>When we want to find the NBA Players, which has the name that begins with “D” letter, the JSON request should be:</p><pre>{<br>    &quot;filterList&quot;: [<br>        {<br>            &quot;name&quot;: &quot;name&quot;,<br>            &quot;value&quot;: &quot;D&quot;,<br>            &quot;operation&quot;: &quot;BEGINS_WITH&quot;<br>        }<br>    ]<br>}</pre><p>The result:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*j-b1mgo1jPBK-gLx9Edh4Q.png" /></figure><h3>Conclusion</h3><p>In this article, I try to explain how to create SQL operations dynamically in a Spring Boot project with the use of Spring Data Specification and Factory Design Pattern. Also, I explained the advantages of Data Specification over Data JPA in some scenarios. If you want to see all code, you can check the <a href="https://github.com/ErogluBaris/db-query-service">github repository</a>.</p><p>The mock database which I queried in my tests was created manually and there are really little data. In order to make some more realistic tests and compare the performance of the db-query-service, we will be using real NBA data in future articles.</p><p>Thanks for reading,</p><p>I wish you happy coding.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c7059c8ff27c" width="1" height="1" alt=""><hr><p><a href="https://medium.com/kocfinanstech/query-service-with-spring-data-specification-and-factory-design-pattern-c7059c8ff27c">Query Service with Spring Data Specification And Factory Design Pattern</a> was originally published in <a href="https://medium.com/kocfinanstech">Koçfinans Tech</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>