<?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 David Kihato on Medium]]></title>
        <description><![CDATA[Stories by David Kihato on Medium]]></description>
        <link>https://medium.com/@kihats?source=rss-95ea87f59839------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*mm-goSKd7oF0J-ZP19TByg.jpeg</url>
            <title>Stories by David Kihato on Medium</title>
            <link>https://medium.com/@kihats?source=rss-95ea87f59839------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Thu, 19 Nov 2026 17:35:14 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@kihats/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[Lombok is NOT DEADL̶o̶m̶b̶o̶k̶ ̶i̶s̶ ̶d̶e̶a̶d̶]]></title>
            <link>https://kihats.medium.com/lombok-is-not-deadl%CC%B6o%CC%B6m%CC%B6b%CC%B6o%CC%B6k%CC%B6-%CC%B6i%CC%B6s%CC%B6-%CC%B6d%CC%B6e%CC%B6a%CC%B6d%CC%B6-77b604f36aec?source=rss-95ea87f59839------2</link>
            <guid isPermaLink="false">https://medium.com/p/77b604f36aec</guid>
            <category><![CDATA[dependency-injection]]></category>
            <category><![CDATA[lombok]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[java-records]]></category>
            <dc:creator><![CDATA[David Kihato]]></dc:creator>
            <pubDate>Wed, 04 Jan 2023 04:59:19 GMT</pubDate>
            <atom:updated>2023-01-04T05:07:43.053Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/509/1*g-tGdhmZOf4YjHdh00rMwg.png" /><figcaption>Image generated on <a href="https://midjourney.com/">midjourney</a></figcaption></figure><h4>Introduction</h4><p>With the introduction of Java 14 in March 2020, the Java language added support for records, which are a concise way to define immutable data classes. With records, the Java compiler generates the equals<em>, </em>hashCode<em>, </em>toString methods as well as the private<em>, </em>final fields and public constructor. Therefore you don’t have to provide the boilerplate code of getters and setters and all-args constructor which most of us used Lombok for. Records rendered Lombok “dead” as some in the community would say.</p><p>However, Lombok is still a useful tool even with the addition of records in Java. In this article, I will highlight several uses of Lombok that will show that it is still highly relevant.</p><h4>1. Logging</h4><p>Logging is an important feature that helps spot mistakes and debug code. It is analogous to the black-box in an airplane. In order to log prior to Lombok, you’d have to include the following static field</p><pre>private static Logger LOGGER = LoggerFactory.getLogger(MySuperApplication.class);</pre><p>to your code. Notice the reference of the owning class MySuperApplication.class. This is important so that the logger may know from where you are logging from. This is quite a mouthful and is prone to mistakes. Copy-pasters would copy the line above and paste it to their classes to avoid typing in each class but it’s prone to mistakes since one might forget to change the class reference. This obviously will print inaccurate information. <br>With Lombok, all you have to do is include @Slf4j annotation to your class and voila, you have logging functionality.</p><pre>@Slf4j<br>public class MySuperApplication {<br>    public static void main(String[] args) {<br>        log.info(&quot;This is an info level message&quot;);<br>    }<br>}</pre><p>Copy-pasters, go ahead and copy-paste the annotation. Logback has your back!</p><h4>2. Exceptions, exceptions, exceptions 🤦</h4><p>You have found a super dupa method and you want to use it in your code but your IDE underlines your code with a red-squiggly line telling you that the exceptions thrown by the method must be handled. What if you don’t care about that exception? What if you just want to ignore it and move on with your life, what do you do? You end up doing the following:</p><pre>public static void main(String[] args) {<br><br>    try {<br>        superDupaMethod();<br>    } catch (Exception e) {<br>        // I don&#39;t care about the exception<br>    }<br>}</pre><p>Fine, the try-catch works, but what does it do to your clean formatted code…arrghhh!</p><p>Enter Lombok!! By just adding @SneakyThrows annotation, it gets rid of the red-squiggly line and you have your clean formatted code intact. Yeah!!!</p><pre>@SneakyThrows<br>public static void main(String[] args) {<br><br>    superDupaMethod();<br>}</pre><h4>3. Builder</h4><p>Suppose you have the following class:</p><pre>public static class Foo {<br>    private Double a, b, c, d, e, f, g, h, i, j, k, l, m, n, o, p, q, r, s, t, u, v, w, x, y, z;<br>}</pre><p>Assuming some of those fields are allowed to be null. How can we instantiate that class? <em>Constructor</em>? — out of the question. Using a constructor is just too much work. What about using <em>setters</em>? Sure, let’s try.</p><pre>public static void main(String[] args) {<br>    var foo = new Foo();<br>    foo.setA(1d);<br>    foo.setE(5d);<br>    foo.setF(6d);<br>    foo.setG(7d);<br>    foo.setY(25d);<br>    foo.setZ(26d);<br>}</pre><p>That works, right? Well…yes, but do we have to repeat foo.<em>, </em>foo..</p><p>Why don’t we see what Lombok has in its bag of cool tricks…</p><p>Enter @Builder!!</p><pre>public static void main(String[] args) {<br>    var foo = Foo.builder().a(1d).e(5d).f(6d).g(7d).y(25d).z(26d).build();<br>}<br><br>@Builder<br>public static class Foo {<br>    @Setter<br>    private Double a, b, c, d, e, f, g, h, i, j, k, l, m, n, o, p, q, r, s, t, u, v, w, x, y, z;<br>}</pre><p>Using the @Builder annotation, Lombok generates a builder pattern for our Foo class and therefore we are able to set our fields using the fluent pattern and construct our class using .build() method. Isn’t that cool, right?!? Lombok generates the boiler plate code for you so that you don’t have to.</p><h4>4. Dependency Injection</h4><p>Spring recommends constructor over field dependency injection. For example the following code snippet is frowned upon.</p><pre>@Component<br>public class MySuperApplication {<br>    @Autowired<br>    EntityManager entityManager;<br>    @Autowired<br>    AService aService;<br>    @Autowired<br>    BService bService;<br>    @Autowired<br>    CService cService;<br>    @Autowired<br>    DService dService;<br>    @Autowired<br>    EService eService;<br>    @Autowired<br>    FService fService;<br>    @Autowired<br>    ARepository aRepository;<br>    @Autowired<br>    BRepository bRepository;<br>    @Autowired<br>    CRepository cRepository;<br>    @Autowired<br>    DRepository dRepository;<br>    @Autowired<br>    ERepository eRepository;<br>    @Autowired<br>    FRepository fRepository;<br>}</pre><p>This is what is recommended:</p><pre>@Component<br>public class MySuperApplication {<br>    EntityManager entityManager;<br>    AService aService;<br>    BService bService;<br>    CService cService;<br>    DService dService;<br>    EService eService;<br>    FService fService;<br>    ARepository aRepository;<br>    BRepository bRepository;<br>    CRepository cRepository;<br>    DRepository dRepository;<br>    ERepository eRepository;<br>    FRepository fRepository;<br><br>    public MySuperApplication(EntityManager entityManager, AService aService, BService bService, CService cService, DService dService, EService eService, FService fService, ARepository aRepository, BRepository bRepository, CRepository cRepository, DRepository dRepository, ERepository eRepository, FRepository fRepository) {<br>        this.entityManager = entityManager;<br>        this.aService = aService;<br>        this.bService = bService;<br>        this.cService = cService;<br>        this.dService = dService;<br>        this.eService = eService;<br>        this.fService = fService;<br>        this.aRepository = aRepository;<br>        this.bRepository = bRepository;<br>        this.cRepository = cRepository;<br>        this.dRepository = dRepository;<br>        this.eRepository = eRepository;<br>        this.fRepository = fRepository;<br>    }<br>}</pre><p>This is too verbose in my opinion and secondly, if I need to add another field, I have to add it in the constructor parameters too and also assign it inside the constructor. That’s just to much work, don’t you think?</p><p>So this is how Lombok helps me to clean up my code. Using the @RequiredArgsConstructor<em> </em>annotation, I am able to achieve the same functionality while keeping my code clean and neat. This annotation generates a constructor with parameters for each uninitialized <em>field</em> marked as final or annotated with @NotNull.</p><pre>@RequiredArgsConstructor<br>@Component<br>public class MySuperApplication {<br>    final EntityManager entityManager;<br>    final AService aService;<br>    final BService bService;<br>    final CService cService;<br>    final DService dService;<br>    final EService eService;<br>    final FService fService;<br>    final ARepository aRepository;<br>    final BRepository bRepository;<br>    final CRepository cRepository;<br>    final DRepository dRepository;<br>    final ERepository eRepository;<br>    final FRepository fRepository;<br>}</pre><p>See how neat my code is. In fact, it’s even better than the first solution where I had to add @Autowired annotations for each field declared.</p><h4>Conclusion</h4><p>In conclusion, Lombok is not dead even with the introduction of records in Java. It is still a valuable tool for reducing boilerplate code and providing useful features that go beyond what records offer. I hope this convinces you not to drop the Lombok library just yet from your project.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=77b604f36aec" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Custom Self-Hosted Maven Repository]]></title>
            <link>https://kihats.medium.com/custom-self-hosted-maven-repository-cbb778031f68?source=rss-95ea87f59839------2</link>
            <guid isPermaLink="false">https://medium.com/p/cbb778031f68</guid>
            <category><![CDATA[reposilite]]></category>
            <category><![CDATA[apache-maven]]></category>
            <category><![CDATA[java]]></category>
            <dc:creator><![CDATA[David Kihato]]></dc:creator>
            <pubDate>Thu, 08 Apr 2021 14:02:34 GMT</pubDate>
            <atom:updated>2021-04-08T14:09:22.201Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/500/1*xuPLQiBNp87cO36yK54BHw.png" /><figcaption><a href="https://www.pngwing.com/en/free-png-vkqhk">Image courtesy of https://www.pngwing.com/en/free-png-vkqhk</a></figcaption></figure><p>Recently, I needed to have a custom self-hosted maven repository for .jar libraries that I had and are not in the Maven Repository or any other public repository. I had to manually install the library to my local repo using the following maven command:</p><pre>mvn install:install-file -Dfile=&lt;Name of jar&gt;.jar -DgroupId=my.group.id -DartifactId=the-artifact -Dversion=1.0.1 -Dpackaging=jar</pre><p>The issue with this is I had to run this command on every server that needed to compile the application. Also for a project with multiple developers, each developer has to run the command to include the dependency in their local repository.</p><h4><strong>Enter Reposilite</strong></h4><p>So I searched for a solution but the solutions were either expensive or too complicated. I just needed a simple one that I can host on my server and have full control over.</p><p>I stumbled upon <a href="https://reposilite.com/">Reposilite</a>, <em>a lightweight repository manager for maven artifacts, </em>as described in their site. And truly, it is lightweight! The jar file’s size is around 23MB and that’s it. That’s all you need!</p><p>This tutorial will take you step by step from installation to deployment of your artifacts. Let’s begin, shall we.</p><h4>Installation</h4><p>Download the .jar file from their <a href="https://github.com/dzikoysk/reposilite/releases">Github</a> and place it in a folder in your server. Ensure you place it inside some empty folder since Resposilite will generate files and folders in the location where the .jar is placed.</p><p>Run the jar file. By default the reposilite application runs on port 80. Since port 80 is common and there is a high probability of it bound to another application, it’s best if you change the default port to something else in the <strong><em>reposilite.cdn</em></strong> config file. The config file is generated on first run. You can also specify a port using the following command:</p><pre>java -Xmx32M -Dreposilite.port=8080 -jar reposilite.jar</pre><p>When the applications starts, it provides a Command Line Interface (CLI) to interact with the application. Just type <em>help </em>to view a list of commands available.</p><h4>Authorization</h4><p>The first step is to create an access token. The elaborate guide provided in their site shows how to manage different users but for simplicity we will create a single user: <em>admin</em>.</p><p>To create the user run the following command in the CLI:</p><pre>keygen &lt;path&gt; &lt;alias&gt; [&lt;permissions&gt;]</pre><pre>e.g.<br>keygen / admin m</pre><p>This will create a new access token for <strong><em>admin </em></strong>with <strong><em>full access</em></strong> permissions.</p><p>Use these credentials to login to the application via a web browser on http://localhost:8080. You should see something like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*msUYAwvuLjHywymWsQSQZg.png" /><figcaption>Reposilite Default Page</figcaption></figure><p>Click on the feather icon on the right and that should take you to the login page. Enter the <strong><em>alias </em></strong>and <strong><em>token </em></strong>(shown on the command line interface after generation).</p><h4>Deployment</h4><p>For the deployment phase, I will show you in two ways:</p><ol><li>Deploy a jar file</li><li>Deploy a project using <strong><em>mvn deploy</em></strong> command</li></ol><h4>1. Deploy a jar file</h4><p>This one is relatively easy.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TEUy-DLyPYQeQgAwAh92hQ.png" /></figure><p>Select the repository from the drop down (releases or snapshot). Enter the groupId, artifactId and version. Drop the jar file in the file drop area and click <strong><em>Generate stub pom file for this artifact</em></strong><em> </em>if you don’t have the .pom (yes I said .pom and not pom.xml) file and click upload. That’s it.</p><h4>2. Deploy a project using mvn deploy command</h4><p>Say you have your own library that you are creating and you need to add as a dependency in your other projects. In your <strong><em>pom.xml </em></strong>file, you need to add the following:</p><pre>&lt;distributionManagement&gt;<br>    &lt;repository&gt;<br>        &lt;id&gt;my-repository&lt;/id&gt;<br>        &lt;url&gt;http://localhost:8080/releases&lt;/url&gt;<br>    &lt;/repository&gt;<br>&lt;/distributionManagement&gt;</pre><p>This points maven on where the artifact should be deployed.</p><p>Also add the following to you <strong><em>~/m2/settings.xml :</em></strong></p><pre>&lt;server&gt;<br>  &lt;!-- Id has to match the id provided in pom.xml --&gt;<br>  &lt;id&gt;my-repository&lt;/id&gt;<br>  &lt;username&gt;{alias}&lt;/username&gt;<br>  &lt;password&gt;{token}&lt;/password&gt;<br>&lt;/server&gt;</pre><p>Remember <strong><em>alias </em></strong>and <strong><em>token </em></strong>are the ones you generated in the authorization step.</p><p>If everything has been setup correctly, go ahead and run the maven command:</p><pre>mvn deploy</pre><p>This will deploy your artifact to the repository.</p><p>To use the dependencies in your other projects, create the dependency in you <strong><em>pom.xml </em></strong>and add your custom repository as a repository entry in the pom.xml</p><pre>&lt;dependencies&gt;<br>    &lt;dependency&gt;<br>        &lt;groupId&gt;com.mydomain&lt;/groupId&gt;<br>        &lt;artifactId&gt;my-artifact&lt;/artifactId&gt;<br>        &lt;version&gt;1.0.1&lt;/version&gt;<br>    &lt;/dependency&gt;<br>&lt;/dependencies&gt;</pre><pre>&lt;repositories&gt;<br>&lt;!--Your custom maven repo--&gt;<br>    &lt;repository&gt;<br>        &lt;id&gt;my-repository&lt;/id&gt;<br>        &lt;name&gt;My custom maven repo&lt;/name&gt;<br>        &lt;url&gt;http://localhost:8080&lt;/url&gt;<br>    &lt;/repository&gt;<br>&lt;/repositories&gt;</pre><p>… and voila, you have your self hosted custom maven repository!!!</p><h3>Conclusion</h3><p>We have seen how to create a custom self hosted maven repository using Reposilite. Reposilite is really lightweight but powerful and I would encourage you to visit their documentation page for further configuration information.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=cbb778031f68" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Dynamic Queries with Querydsl-JPA]]></title>
            <link>https://kihats.medium.com/querying-with-querydsl-jpa-abd2e722dc19?source=rss-95ea87f59839------2</link>
            <guid isPermaLink="false">https://medium.com/p/abd2e722dc19</guid>
            <category><![CDATA[spring-boot]]></category>
            <category><![CDATA[jpa]]></category>
            <category><![CDATA[querydsl]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[hibernate]]></category>
            <dc:creator><![CDATA[David Kihato]]></dc:creator>
            <pubDate>Tue, 24 Dec 2019 04:41:00 GMT</pubDate>
            <atom:updated>2024-10-04T12:24:09.116Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*riZsouf2AINzb5Et-AUrQg.jpeg" /><figcaption>Image by <a href="https://pixabay.com/users/qimono-1962238/?utm_source=link-attribution&amp;utm_medium=referral&amp;utm_campaign=image&amp;utm_content=1495858">Arek Socha</a> from <a href="https://pixabay.com/?utm_source=link-attribution&amp;utm_medium=referral&amp;utm_campaign=image&amp;utm_content=1495858">Pixabay</a></figcaption></figure><p><strong>Pre-Intro</strong></p><p>Pssstt, hey you, yes you! How do you make database queries from your java application? Lemmi guess, you either use native queries i.e. (“select * from books”)or you use Spring Data JPA’s methods such as findAll(),findByStatus() etc. So, here is the challenge of using these two methods <br>1. For native queries, you are prone to making errors/typos and writing dynamic queries could be a problem<br>2. For JPA methods, well, it has some form of type-safety in it but it might be difficult to write complex dynamic queries</p><p>What if I told you that you can mash-up the two and end up with a powerful tool. Enter <strong>QueryDsl!!!!</strong></p><h4>Introduction</h4><p>Querydsl provides a typesafe querying layer on top of JPA, JDO, JDBC and other backends. It maps your domain models to generated typesafe classes called Q-Classes (since they are preceded with letter ‘Q’). The advantage of QueryDsl is, it provides syntax similar to SQL for querying therefore it’s not a steep learning curve for beginners especially with a background in SQL.</p><p><em>(For sure that intro was a bit of a mouthful, I agree. Let me explain in a very simple way)</em></p><h4><strong>Simplified Intro</strong></h4><p>Say you have the following entity (domain model), Cat</p><pre>@Entity<br>@Table(name = &quot;cat&quot;)<br>public class Cat {</pre><pre>    @Id<br>    @GeneratedValue(strategy = GenerationType.<em>IDENTITY</em>)<br>    private Long id;<br>    <br>    private String name;</pre><pre>    private int age;</pre><pre>    // Getters and setters</pre><pre>}</pre><p>A plugin, as will be explained later, will generate some classes that we call ‘Q’-classes. So you will have a QCat class that is just the name of your entity preceded with a ‘Q’ in some folder generated-sources . These Q-classes will be used in the querying process. See the following example with it’s associated SQL query.</p><pre>QCat qcat = QCat.cat; // Remember the QCat was generated by the        <br>                      // querydsl plugin</pre><pre>JPQLQuery&lt;?&gt; query = new JPAQuery&lt;&gt;(entityManager); // To be<br>                                                    // explained<br>                                                    // later<br>// Let&#39;s query<br>List&lt;Cat&gt; catList = query.select(qcat)<br>                         .from(qcat)<br>                         .where(qcat.name.like(&quot;%kitty%&quot;))                         <br>                         .offset(0)<br>                         .limit(10)<br>                         .orderBy(qcat.id.desc()) <br>                         .fetch();</pre><pre>// The native SQL Query<br>select * from cat <br>where name like &#39;%kitty%&#39;<br>order by id desc<br>limit 0, 10;</pre><p>See how easy that was!! Notice how similar-like the querying is to SQL? Let’s now setup and get to learn more on this awesome library.</p><h4>Setting up</h4><p>Let’s set up, shall we. We are going to use the popular framework — <em>Spring Boot</em>, <em>MySql</em> and <em>Maven</em> as our build tool.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/53ea52e37baad535669685ea2ca4760c/href">https://medium.com/media/53ea52e37baad535669685ea2ca4760c/href</a></iframe><p>In the pom.xml we’ve included a starter pack for JPA and web but of most importance is the QueryDsl dependencies querydsl-apt and querydsl-jpa. Also, still in the pom.xml we require a plugin, under build-&gt;plugin XML tags, for generating Q-classes for you domain models. What it does it scans for all classes annotated with @Entity and generates Q-classes related to your model and generates them to the specified folder outputDirectory, of which in our case is the project build directory in the generated-sources folder. These Q-classes are of great importance when it comes to querying as we will see later in this article.</p><p><strong>Domain Models</strong></p><p>Let’s create our domain models. We only have three for this example: Student, Subject and a many-to-many resolver StudentSubject (since a student can take many subjects and a subject can be taken by many students)</p><p>Here is our entity relationship</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/691/1*ch3msmT1NWPmxaBa2rC23A.png" /><figcaption>Entity Relationship</figcaption></figure><p>… and the models are as below:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5e0ec01f7c1fc05140072641436b7f32/href">https://medium.com/media/5e0ec01f7c1fc05140072641436b7f32/href</a></iframe><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5982d10f7582a42198aea148aabb380b/href">https://medium.com/media/5982d10f7582a42198aea148aabb380b/href</a></iframe><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/af1f274ee20ec63a1b133f95f3bb4086/href">https://medium.com/media/af1f274ee20ec63a1b133f95f3bb4086/href</a></iframe><p>There goes our domain models, simple and straight forward POJOs.</p><p>So let’s generate our Q-classes from these entities.</p><p><strong>Generating </strong><strong>Q-Classes with Different IDEs</strong></p><p><strong><em>Maven</em></strong></p><p><em>(Yeah, yeah, I know </em><em>Maven is not an IDE but lemmi just squeeze it in here)</em></p><p>To generate Q-classes with maven all you have to do is build as you’d do it normally mvn clean package. The Q-classes will be generated to the specified folder in the pom.xml .</p><p><strong><em>Intellij</em></strong></p><p>With Intellij you can go to the buildmenu and select Build Project as shown in the image below</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/300/1*oAfBFqU9gzJgwqqgbV_K1Q.png" /><figcaption>Generate Q-classes from Build — Intellij</figcaption></figure><p>or you can select Generate Sources and Update folders under the Maven side bar on the top right hand corner of your IDE</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/701/1*8_GhVXfY6IWvmYKTURO9iQ.png" /><figcaption>Generate Sources — Intellij</figcaption></figure><p>The generated sources will appear as below</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/457/1*TCFs3yiIgLnvHPYJDaIKMg.png" /><figcaption>The generated Q-classes</figcaption></figure><p>If by any chance Intellij cannot find the Q-classes through code completion, go to File&gt;Project Structure menu. A dialog appears and select Modules as below and ensure generated-sources is a Sources type. So you just click on the folder generated-sources and then click Sources at the top and you’ll make your generated-sources folder a Sources folder.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YLbtXDdZkfLDAOHbQje-UA.png" /></figure><p><strong><em>Netbeans</em></strong></p><p>For Netbeans it’s really straight forward. Just build your project and voila, your Q-classes will be generated.</p><h4><strong>Business Logic</strong></h4><p>So, we have our domain models and our Q-classes. So, why don’t we go ahead and write our business logic, shall we…</p><p>In our first case lets write a simple query to fetch all Students whose firstname or lastname contains a specified string.</p><p>In order to do this we need to @Autowire an EntityManager in our @Service class (Business logic class). Then we create a method that does our query.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e71acc21d068895bec80978a410b4b21/href">https://medium.com/media/e71acc21d068895bec80978a410b4b21/href</a></iframe><p>In our method, we need to instantiate a JPQLQuery, an interface, which we will use for the querying process and instantiate it to a JPAQuery which expects an EntityManager in it’s constructor.</p><pre>JPQLQuery&lt;?&gt; query = new JPAQuery&lt;&gt;(entityManager);</pre><p><em>So, why create a </em><em>JPQLQuery(interface) type whereas you can just create a </em><em>JPAQuery(concrete class) type. Well, just peruse the internet and good design requires us to program to interface and not to concrete class. For example when instantiating a </em><em>List, this is what we do </em><em>List myList = new ArrayList(). Rarely do you find one doing this: </em><em>ArrayList myList = new ArrayList(); (this code just smells).</em></p><p>Now that we have our querying object, we need to instantiate our Q-classes which we will use together with our querying object to write queries almost similar to SQL. Since these Q-classes are already generated for us, let’s go ahead and instantiate a QStudent object using it’s public field.</p><pre>QStudent qstudent = QStudent.<em>student</em>;</pre><p>Now that we have all we need, let’s go ahead and construct the query. query.select(qstudent) — similar to select * from ...</p><p>.from(qstudent) — similar to ... * from Student</p><pre>.where(qstudent.firstname.like(&quot;%&quot; + str + &quot;%&quot;).or(qstudent.lastname.like(&quot;%&quot; + str + &quot;%&quot;)))</pre><p>— similar to ... where(firstname like &#39;%val%&#39; or lastname like &#39;%val%&#39;.</p><p>.fetch() — terminates our query and requests for the results.</p><p>Pretty straight forward, right?</p><p>Let’s go ahead and test. I have added the following data in my student table:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/382/1*uR1V6HeW_eNptMcsBqILgA.png" /><figcaption>Student table data</figcaption></figure><p>I created a simple Controller to help me test using the popular tool Postman.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1c034c9e87337590bd290b60505af4ab/href">https://medium.com/media/1c034c9e87337590bd290b60505af4ab/href</a></iframe><p>… and here are the results when I fetch using ‘d’ and ‘j’ as the search string:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/307/1*xAoC1xd_LN_rx_OqstXS5w.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/275/1*1e2EqNbinVzeyOCd_XhITQ.png" /><figcaption>Querying with ‘d’ and ‘j’ respectively</figcaption></figure><p>Let’s go ahead and write another query to count the number of students taking a particular subject using the data below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/414/1*-E2uiaqBMWOJe6mxp9a2NQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/360/1*KQJc1_aRoh1kS1mU43IxnQ.png" /><figcaption>Student-Subject Mapping</figcaption></figure><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d7cdffa7976aa115e87e6bd41b1691d3/href">https://medium.com/media/d7cdffa7976aa115e87e6bd41b1691d3/href</a></iframe><p>… and using Postman using parameters ‘Maths’ and ‘Chemistry’ returns the correct results 2 and 1 respectively.</p><p>Finally, let’s write a query that changes at runtime based on what the user prefers. We are going to write a query that fetches all students whose firstname or lastname is equal to the string passed. The user will determine which column to search from by passing a letter i.e. f for firstname and l for lastname .</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/408d5325566847dbc0e1e59fbf43d873/href">https://medium.com/media/408d5325566847dbc0e1e59fbf43d873/href</a></iframe><p>And here are the tests done on Postman:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/577/1*jFeDtTNElXKmBveNJuUBXw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/565/1*Ogo0FfSe9FiTcGSvyb_nIA.png" /></figure><h4>Remarks</h4><p>We have learnt how to include QueryDsl into our project, generate Q-classes and use the Q-classes generated in querying.</p><p>We can do all sorts of querying similar to SQL such as avg, max, min, joins, order by, group by and so on and so fourth. The list is endless.</p><h4>Cons</h4><p>QueryDsl JPA is a great and simple tool for querying but has some drawbacks which QueryDsl SQL has provided solutions for. For example, QueryDsl JPA cannot be used in querying unrelated tables using joins since a path is required from one Q-class to another.</p><p>As much as QueryDsl is a great tool for querying, things can get a little bit messy when it comes to very complex queries (say, analytics queries) because it makes your code even more complex.</p><h4>Conclusion</h4><p>The choice of an ORM or querying tool lies entirely on the user there being numerous technologies out there such as: Hibernate, Criteria Api, Query Dsl/Sql, JOOQ to name just a few. But QueryDsl JPA has proven to be a great tool that has type safety and really works well with dynamic queries. As a user it’s your obligation to check them out and choose the one that best suites you.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=abd2e722dc19" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>