<?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 Paul ‘Tofunmi O. on Medium]]></title>
        <description><![CDATA[Stories by Paul ‘Tofunmi O. on Medium]]></description>
        <link>https://medium.com/@paultofunmi?source=rss-e6e4f6ff5fad------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*DgbYY63ep1trQHLRBijkfw.jpeg</url>
            <title>Stories by Paul ‘Tofunmi O. on Medium</title>
            <link>https://medium.com/@paultofunmi?source=rss-e6e4f6ff5fad------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 24 Nov 2026 02:42:05 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@paultofunmi/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[Creating Documentation for Rest Api]]></title>
            <link>https://medium.com/zero-to-production/creating-documentation-for-rest-api-e48eecaf4def?source=rss-e6e4f6ff5fad------2</link>
            <guid isPermaLink="false">https://medium.com/p/e48eecaf4def</guid>
            <category><![CDATA[rest-api-documentation]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[swagger-ui]]></category>
            <dc:creator><![CDATA[Paul ‘Tofunmi O.]]></dc:creator>
            <pubDate>Mon, 15 Apr 2019 13:37:42 GMT</pubDate>
            <atom:updated>2019-04-15T13:37:42.159Z</atom:updated>
            <content:encoded><![CDATA[<p>Using Swagger to create meaningful documentation in Spring Boot</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7ZMMQtP4tuS9PCVqP5MhgQ.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/photos/tofagMI_UCM?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Jan Mellström</a> on <a href="https://unsplash.com/search/photos/piles-of-books?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><p>In the past, creating documentations used to be a chore most developers. However, we Swagger, we can annotate our classes. The only disadvantage is that we will be mixing Swagger annotations in our classes.</p><p>Let’s get started.</p><p>In this tutorial, we will use one of our REST tutorials, in which we built a simple REST API with CRUD functionalities. <a href="https://github.com/zero-to-production/bucketlist">You can get a copy from Github</a>.</p><p>Swagger offers lots of annotation for use in the classes however, we these ones below:</p><ul><li>@Api — anotates class as a Swagger resource.</li><li>@ApiModel Provides additional information about Swagger models.</li><li>@ApiModelProperty: Adds and manipulates data of a model property.</li><li>@ApiResponses: Provides a wrapper for defining a list of multiple ApiResponse objects.</li><li>@ApiResponse Annotates a single response of an operation.</li><li>@ApiOperation Annotates an operation or typically an HTTP method against a specific path.</li></ul><p><a href="https://github.com/swagger-api/swagger-core/wiki/annotations">The full list of annotations is available here</a></p><p>Tools /Resources for this guide:</p><ul><li>Maven dependences</li><li>IDE</li></ul><p>We need the following dependencies</p><pre>&lt;dependency&gt;<br>   &lt;groupId&gt;io.springfox&lt;/groupId&gt;<br>   &lt;artifactId&gt;springfox-swagger2&lt;/artifactId&gt;<br>   &lt;version&gt;2.6.1&lt;/version&gt;<br>   &lt;scope&gt;compile&lt;/scope&gt;<br>&lt;/dependency&gt;</pre><pre>&lt;dependency&gt;<br>   &lt;groupId&gt;io.springfox&lt;/groupId&gt;<br>   &lt;artifactId&gt;springfox-swagger-ui&lt;/artifactId&gt;<br>   &lt;version&gt;2.6.1&lt;/version&gt;<br>   &lt;scope&gt;compile&lt;/scope&gt;<br>&lt;/dependency&gt;</pre><p>I left the scope as compile because I want it to be available users after we have compiled it.</p><p>The complete Pom.xml file for our project is:</p><pre>&lt;?xml version=&quot;1.0&quot; encoding=&quot;UTF-8&quot;?&gt;<br>&lt;project xmlns=&quot;http://maven.apache.org/POM/4.0.0&quot; xmlns:xsi=&quot;http://www.w3.org/2001/XMLSchema-instance&quot;<br>   xsi:schemaLocation=&quot;http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd&quot;&gt;<br>   &lt;modelVersion&gt;4.0.0&lt;/modelVersion&gt;<br>   &lt;parent&gt;<br>      &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt;<br>      &lt;artifactId&gt;spring-boot-starter-parent&lt;/artifactId&gt;<br>      &lt;version&gt;2.1.3.RELEASE&lt;/version&gt;<br>      &lt;relativePath/&gt; &lt;!-- lookup parent from repository --&gt;<br>   &lt;/parent&gt;<br>   &lt;groupId&gt;com.zerotoproduction&lt;/groupId&gt;<br>   &lt;artifactId&gt;bucketlist&lt;/artifactId&gt;<br>   &lt;version&gt;0.0.1-SNAPSHOT&lt;/version&gt;<br>   &lt;name&gt;bucketlist&lt;/name&gt;<br>   &lt;description&gt;A bucketlist rest api stored in mysql dband deployed to heroku&lt;/description&gt;<br><br>   &lt;properties&gt;<br>      &lt;java.version&gt;1.8&lt;/java.version&gt;<br>   &lt;/properties&gt;<br><br>   &lt;dependencies&gt;<br>      &lt;dependency&gt;<br>         &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt;<br>         &lt;artifactId&gt;spring-boot-starter-data-jpa&lt;/artifactId&gt;<br>      &lt;/dependency&gt;<br>      &lt;dependency&gt;<br>         &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt;<br>         &lt;artifactId&gt;spring-boot-starter-web&lt;/artifactId&gt;<br>      &lt;/dependency&gt;<br>      &lt;dependency&gt;<br>         &lt;groupId&gt;io.springfox&lt;/groupId&gt;<br>         &lt;artifactId&gt;springfox-swagger2&lt;/artifactId&gt;<br>         &lt;version&gt;2.6.1&lt;/version&gt;<br>         &lt;scope&gt;compile&lt;/scope&gt;<br>      &lt;/dependency&gt;<br>      &lt;dependency&gt;<br>         &lt;groupId&gt;org.springframework&lt;/groupId&gt;<br>         &lt;artifactId&gt;spring-webmvc&lt;/artifactId&gt;<br>      &lt;/dependency&gt;<br>      &lt;dependency&gt;<br>         &lt;groupId&gt;io.springfox&lt;/groupId&gt;<br>         &lt;artifactId&gt;springfox-swagger-ui&lt;/artifactId&gt;<br>         &lt;version&gt;2.6.1&lt;/version&gt;<br>         &lt;scope&gt;compile&lt;/scope&gt;<br>      &lt;/dependency&gt;<br><br>      &lt;dependency&gt;<br>         &lt;groupId&gt;mysql&lt;/groupId&gt;<br>         &lt;artifactId&gt;mysql-connector-java&lt;/artifactId&gt;<br>         &lt;scope&gt;runtime&lt;/scope&gt;<br>      &lt;/dependency&gt;<br>      &lt;dependency&gt;<br>         &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt;<br>         &lt;artifactId&gt;spring-boot-starter-test&lt;/artifactId&gt;<br>         &lt;scope&gt;test&lt;/scope&gt;<br>      &lt;/dependency&gt;<br>   &lt;/dependencies&gt;<br><br>   &lt;build&gt;<br>      &lt;plugins&gt;<br>         &lt;plugin&gt;<br>            &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt;<br>            &lt;artifactId&gt;spring-boot-maven-plugin&lt;/artifactId&gt;<br>         &lt;/plugin&gt;<br>      &lt;/plugins&gt;<br>   &lt;/build&gt;<br>&lt;/project&gt;</pre><h3>Configuring Swagger 2</h3><p>By customizing Swagger, we are providing information about our Api in a class with the necessary annotation. Springfox group id provides @EnableSwagger2 annotation which indicates that Swagger support should be enabled. We should also annotate the class with the @Configuration annotation. A Docket bean holds the configuration.</p><p>You need to do some cleaning up.</p><p>First create the following packages: config, controller, model and repository.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/259/1*Rjp4C7E2N7iikQtis4z9Sg.png" /><figcaption>This is the folder structure</figcaption></figure><p>Our Swagger config looks like this:</p><pre>package com.zerotoproduction.bucketlist.config;<br><br>import org.springframework.context.annotation.Bean;<br>import org.springframework.context.annotation.Configuration;<br>import org.springframework.http.ResponseEntity;<br>import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;<br>import org.springframework.web.servlet.config.annotation.ViewControllerRegistry;<br>import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;<br>import springfox.documentation.builders.ApiInfoBuilder;<br>import springfox.documentation.builders.PathSelectors;<br>import springfox.documentation.builders.RequestHandlerSelectors;<br>import springfox.documentation.service.ApiInfo;<br>import springfox.documentation.spi.DocumentationType;<br>import springfox.documentation.spring.web.plugins.Docket;<br>import springfox.documentation.swagger2.annotations.EnableSwagger2;<br><br>import java.time.LocalDate;<br><br>@EnableSwagger2<br>@Configuration<br>public class SwaggerConfig implements WebMvcConfigurer {<br>   <br>   public SwaggerConfig() {<br>      super();<br>   }<br><br>   @Bean<br>   public Docket mainConfig() {<br>      return new Docket(DocumentationType.<em>SWAGGER_2</em>)<br>               .apiInfo(apiInfo())<br>               .select().apis(RequestHandlerSelectors.<em>any</em>())<br>               .apis(RequestHandlerSelectors.<em>basePackage</em>(&quot;com.zerotoproduction.bucketlist.controller&quot;))<br>               .paths(PathSelectors.<em>regex</em>(&quot;/.*&quot;))<br>               .build()<br>               .directModelSubstitute(LocalDate.class, String.class)<br>               .genericModelSubstitutes(ResponseEntity.class)<br>               ;<br>   }<br><br>   @Override<br>   public void addViewControllers(ViewControllerRegistry registry) {<br>       registry.addRedirectViewController(&quot;/api/v2/api-docs&quot;, &quot;/v2/api-docs&quot;);<br>       registry.addRedirectViewController(&quot;/api/swagger-resources/configuration/ui&quot;, &quot;/swagger-resources/configuration/ui&quot;);<br>       registry.addRedirectViewController(&quot;/api/swagger-resources/configuration/security&quot;, &quot;/swagger-resources/configuration/security&quot;);<br>       registry.addRedirectViewController(&quot;/api/swagger-resources&quot;, &quot;/swagger-resources&quot;);<br>   }<br><br>   @Override<br>   public void addResourceHandlers(ResourceHandlerRegistry registry) {<br>       registry.addResourceHandler(&quot;/api/swagger-ui.html**&quot;).addResourceLocations(&quot;classpath:/META-INF/resources/swagger-ui.html&quot;);<br>       registry.addResourceHandler(&quot;/api/webjars/**&quot;).addResourceLocations(&quot;classpath:/META-INF/resources/webjars/&quot;);<br>   }<br><br>   private ApiInfo apiInfo() {<br><br>       return new ApiInfoBuilder()<br><br>       .title(&quot;Bucket List Rest API&quot;)<br><br>       .description(&quot;This page lists all the rest apis for Bucket List API.&quot;)<br><br>       .version(&quot;1.0&quot;)<br><br>       .build();<br><br>   }<br>}</pre><p>Here is the screenshot of the generated docs:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*voycFjLN-yqGQ3DWuT8PgA.png" /></figure><p>Using Swagger docs, you don’t need to use Postman as you can test your api calls from Swagger.</p><p>Get the complete code:</p><p><a href="https://github.com/zero-to-production/bucketlist-swagger">https://github.com/zero-to-production/bucketlist-swagger</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e48eecaf4def" width="1" height="1" alt=""><hr><p><a href="https://medium.com/zero-to-production/creating-documentation-for-rest-api-e48eecaf4def">Creating Documentation for Rest Api</a> was originally published in <a href="https://medium.com/zero-to-production">Zero To Production</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Understanding Functional Programming in Java 8]]></title>
            <link>https://medium.com/zero-to-production/understanding-functional-programming-in-java-8-d6b9df249b3f?source=rss-e6e4f6ff5fad------2</link>
            <guid isPermaLink="false">https://medium.com/p/d6b9df249b3f</guid>
            <category><![CDATA[java]]></category>
            <category><![CDATA[functional-programming]]></category>
            <category><![CDATA[java8]]></category>
            <dc:creator><![CDATA[Paul ‘Tofunmi O.]]></dc:creator>
            <pubDate>Mon, 15 Apr 2019 11:17:26 GMT</pubDate>
            <atom:updated>2019-04-15T11:45:20.255Z</atom:updated>
            <content:encoded><![CDATA[<p>Learn about lambda, filter, streams, method reference, consumer and predicate.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yX0uameYIGWqCbM6buaUsg.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/photos/BB6YpCHmW3I?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Tevin Trinh</a> on <a href="https://unsplash.com/search/photos/stream?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><h3>What is functional programming?</h3><blockquote>Functional programming is a programming paradigm — a style of building the structure and elements of computer programs — that treats computation as the evaluation of mathematical functions and avoids changing-state and mutable data — Wikipedia</blockquote><p>In functional programming, computations are <strong><em>declared</em></strong> in programming functions. It is declarative because computation logic is expressed without describing the control flow — expressions are used to tell the computer what needs to be done without stating how it should be done. The functions in functional programming are different from functions in imperative programming because functions in imperative produce an output based on the passed arguments whereas functions in imperative programming might rely on state values (or properties of a class) to decide what will be returned.</p><h3>What is Functional programming in Java?</h3><p>In Java 8 release, the creators of Java introduced functional programming with the flagship lambda expressions. In essence, it necessitated a shift in perspective from imperative, object-oriented thinking to declarative functional thinking.</p><p>We will create a Bucket class with properties: name, description and priority (on a scale 1 -10 increasing from least important to most important) to see how this works. Bucket class comes from the idea of a bucket list of places to visit. For example, you might plan to visit the seven wonders before your next birthday. So we create our model to hold this information.</p><pre>package com.zerotoproduction;<br><br>public class Bucket {<br><br>    private String name;<br>    private String description;<br>    private int priority;<br><br>    public Bucket(String name, String description, int priority) {<br>        this.name = name;<br>        this.description = description;<br>        this.priority = priority;<br>    }<br><br>    public String getName() {<br>        return name;<br>    }<br><br>    public void setName(String name) {<br>        this.name = name;<br>    }<br><br>    public String getDescription() {<br>        return description;<br>    }<br><br>    public void setDescription(String description) {<br>        this.description = description;<br>    }<br><br>    public int getPriority() {<br>        return priority;<br>    }<br><br>    public void setPriority(int priority) {<br>        this.priority = priority;<br>    }<br><br>    @Override<br>    public String toString() {<br>        return &quot;Bucket{&quot; +<br>                &quot;name=&#39;&quot; + name + &#39;\&#39;&#39; +<br>                &quot;, description=&#39;&quot; + description + &#39;\&#39;&#39; +<br>                &quot;, priority=&quot; + priority +<br>                &#39;}&#39;;<br>    }<br><br><br>}</pre><p>Now, let us create a class to run our program</p><pre>package com;<br><br>import com.zerotoproduction.Bucket;<br><br>import java.util.ArrayList;<br>import java.util.List;<br><br>public class BucketTestMain {<br><br>    public static void printBuckets1(List&lt;Bucket&gt; buckets)<br>    {<br><br>        for (Bucket b: buckets)<br><br>            if (b.getPriority() &gt; 7)<br><br>                System.<em>out</em>.println(b);<br><br>    }<br><br>    public static void printBuckets2(List&lt;Bucket&gt; buckets)<br>    {<br><br>        buckets.stream()<br><br>                .filter(bucket -&gt; bucket.getPriority() &gt; 7)<br><br>                .forEach(bucket -&gt; System.<em>out</em>.println(bucket));<br><br>    }<br><br>    public static void main(String[] args){<br>        List&lt;Bucket&gt; myBuckets = new ArrayList&lt;Bucket&gt;();<br>        myBuckets.add(new Bucket(&quot;Visit  Coliseum, Rome, Italy&quot;, &quot;The Coliseum, also known as the Flavian Amphitheatre, is an oval amphitheatre in the centre of the city of Rome, Italy. Built of travertine, tuff, and brick-faced concrete, it is the largest amphitheatre ever built&quot;, 1));</pre><pre>        myBuckets.add(new Bucket(&quot;Visit  Christ the Redeemer Statue, Rio de Janeiro, Brazil&quot;, &quot;Christ the Redeemer is an Art Deco statue of Jesus Christ in Rio de Janeiro, Brazil, created by French sculptor Paul Landowski&quot;, 3));</pre><pre>        myBuckets.add(new Bucket(&quot;Visit  Taj Mahal, India&quot;, &quot;The Taj Mahal is an ivory-white marble mausoleum on the south bank of the Yamuna river in the Indian city of Agra. It was commissioned in 1632&quot;, 6));</pre><pre>        myBuckets.add(new Bucket(&quot;Visit  Great Wall of China, China&quot;, &quot;Built between the 5th century B.C. and the 16th century, the Great Wall of China is a stone-and-earth fortification created to protect the borders of the Chinese Empire from invading Mongols. The Great Wall is actually a succession of multiple walls spanning approximately 4,000 miles, making it the world&#39;s longest manmade structure&quot;, 8));<br><br><br>        BucketTestMain.<em>printBuckets2</em>(myBuckets);<br>        System.<em>out</em>.printf(&quot;%n%n&quot;);<br>        System.<em>out</em>.printf(&quot;---Imperative---%n%n&quot;);<br>        BucketTestMain.<em>printBuckets1</em>(myBuckets);<br>    }<br><br>}</pre><p>In our main method, we have initialized the ArrayList with four buckets. However, we have two print methods. The first uses imperative pattern with a for statement for looping and if statement to ensure that only buckets with priority higher than 7 is returned.</p><p>The second method makes use of functional programming paradigms. Let’s dig deeper</p><pre>buckets.stream()<br><br>                .filter(bucket -&gt; bucket.getPriority() &gt; 7)<br><br>                .forEach(bucket -&gt; System.<em>out</em>.println(bucket));</pre><p>buckets.stream returns a Stream Interface holding buckets like so: Stream&lt;Bucket&gt;. Imagine a stream to be consisting of elements. So, we can replace buckets.stream() like so:</p><pre>Stream&lt;Bucket&gt; bucketStream = buckets.stream();<br>bucketStream<br>        .filter(bucket -&gt; bucket.getPriority() &gt; 7)<br>        .forEach(bucket -&gt; System.<em>out</em>.println(bucket));</pre><p>The stream can be filtered to return a stream consisting of elements that match a predicate.</p><p>Looking into the source code, you can see that the Stream Interface has a filter method that returns a Stream and accepts an argument of type Predicate.</p><pre>public interface Stream&lt;T&gt; extends BaseStream&lt;T, Stream&lt;T&gt;&gt; {<br><em><br>    </em>Stream&lt;T&gt; filter(Predicate&lt;? super T&gt; predicate);<br>}</pre><p>The Predicate handles the task of determining what passes through our filter. In the docs, Predicate is a functional interface with a test method.</p><pre>@FunctionalInterface<br>public interface Predicate&lt;T&gt; {<br><br>    <em>/**<br>     * Evaluates this predicate on the given argument.<br>     *<br>     * </em><strong><em>@param </em></strong><em>t the input argument<br>     * </em><strong><em>@return </em></strong><em>{</em><strong><em>@code </em></strong><em>true} if the input argument matches the predicate,<br>     * otherwise {</em><strong><em>@code </em></strong><em>false}<br>     */<br>    </em>boolean test(T t);</pre><p>Armed with this knowledge, we can replace our filtering function like so:</p><pre>buckets.stream()<br>        .filter(new Predicate&lt;Bucket&gt;() {<br>                public boolean test(Bucket bucket){<br>                    return bucket.getPriority() &gt; 7;<br>                }<br>        })<br>        .forEach(bucket -&gt; System.<em>out</em>.println(bucket));</pre><p>The above piece works perfectly. The filter function also returns a stream.</p><p>However, with functional programming, we just declare what we want. So lets revert back to this:</p><pre>buckets.stream()<br>        .filter(bucket -&gt; bucket.getPriority() &gt; 7)<br>        .forEach(bucket -&gt; System.<em>out</em>.println(bucket));</pre><p>Now, lets look at the forEach block.</p><p>The forEach block accepts a Consumer. The Consumer is equally a functional Interface that expects the accept method. This method declares what would be done with each item. In our case, we print each bucket.</p><pre>@FunctionalInterface<br>public interface Consumer&lt;T&gt; {<br><br>    <em>/**<br>     * Performs this operation on the given argument.<br>     *<br>     * </em><strong><em>@param </em></strong><em>t the input argument<br>     */<br>    </em>void accept(T t);<br>}</pre><p>Here is our adjusted code with Consumer interface and accept method. The code below works perfectly.</p><pre>buckets.stream()<br>        .filter(bucket -&gt; bucket.getPriority() &gt; 7)<br>        .forEach(new Consumer&lt;Bucket&gt;(){<br>            @Override<br>            public void accept(Bucket b){<br>                System.<em>out</em>.println(b);<br>            }<br>        });</pre><p>Let’s revert back to the simplified functional logic to learn about method reference. After reverting this is what we have:</p><pre>bucketStream<br>        .filter(bucket -&gt; bucket.getPriority() &gt; 7)<br>        .forEach(bucket -&gt; System.<em>out</em>.println(bucket));</pre><p>So we can see that with lambda expressions, we have shortened and simplified the code base. See an example below:</p><p>From</p><pre>.filter(new Predicate&lt;Bucket&gt;() {<br>                public boolean test(Bucket bucket){<br>                    return bucket.getPriority() &gt; 7;<br>                }<br>        })</pre><p>to</p><pre>.filter(bucket -&gt; bucket.getPriority() &gt; 7)</pre><p>and the consumer from</p><pre>.forEach(new Consumer&lt;Bucket&gt;(){<br>            @Override<br>            public void accept(Bucket b){<br>                System.<em>out</em>.println(b);<br>            }<br>        });</pre><p>to</p><pre>.forEach(bucket -&gt; System.<em>out</em>.println(bucket));</pre><h3>So what are Lambda Expressions?</h3><p>Lambda expressions expose instances of functional interfaces — such as Consumer and Predicate shown above — with a single abstract method.</p><p>It was added to Java 8 to provide the following:</p><ul><li>A function that can be created without belonging to any class.</li><li>Lambda expressions that can passed around in a chain and used as if it were an object.</li></ul><p>The syntax is</p><pre>lambda operator -&gt; body</pre><p>Zero operators do not need the parenthesis, so either of these would work.</p><p>Without parenthesis:</p><pre>bucket -&gt; System.<em>out</em>.println(bucket)</pre><p>With parenthesis:</p><pre>(bucket) -&gt; System.<em>out</em>.println(bucket)</pre><p>Now with method reference, we can simplify our code from this(before) to after.</p><p>Before</p><pre>bucketStream<br>        .filter( (bucket) -&gt; bucket.getPriority() &gt; 7)<br>        .forEach( (bucket) -&gt; System.<em>out</em>.println(bucket));</pre><p>To this:</p><pre>bucketStream<br>        .filter( (bucket) -&gt; bucket.getPriority() &gt; 7)<br>        .forEach( System.<em>out</em>::println);</pre><p>We are automatically calling the print method with each value from forEach.</p><p>Let’s take it a step higher by abstracting the filter logic to a function and use method reference.</p><p>First, let us extract that logic into a method like so:</p><pre>bucketStream<br>        .filter( (bucket) -&gt; <em>isaAboveNumber</em>(bucket))<br>        .forEach( System.<em>out</em>::println);</pre><p>Here is the logic in a new method.</p><pre>private static boolean isaAboveNumber(Bucket bucket) {<br>    return bucket.getPriority() &gt; 7;<br>}</pre><p>Next, let apply method reference.</p><pre>bucketStream<br>        .filter( BucketTestMain::<em>isaAboveNumber</em>)<br>        .forEach( System.<em>out</em>::println);</pre><p>Because it is static method, we used the class name followed by (::) and method name. By using method reference (::), Java knows that it would pass the argument to the function.</p><p>By now, you would have seen how code base can be simplified using functional programming in Java.</p><p>The code base will be available on github here:</p><p><a href="https://github.com/zero-to-production/functional-programming">https://github.com/zero-to-production/functional-programming</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d6b9df249b3f" width="1" height="1" alt=""><hr><p><a href="https://medium.com/zero-to-production/understanding-functional-programming-in-java-8-d6b9df249b3f">Understanding Functional Programming in Java 8</a> was originally published in <a href="https://medium.com/zero-to-production">Zero To Production</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Supercharge your code quality using SonarLint]]></title>
            <link>https://medium.com/zero-to-production/supercharge-your-code-quality-using-sonarlint-f175b6095ecb?source=rss-e6e4f6ff5fad------2</link>
            <guid isPermaLink="false">https://medium.com/p/f175b6095ecb</guid>
            <category><![CDATA[java]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[linter]]></category>
            <category><![CDATA[lint]]></category>
            <category><![CDATA[sonarlint]]></category>
            <dc:creator><![CDATA[Paul ‘Tofunmi O.]]></dc:creator>
            <pubDate>Mon, 15 Apr 2019 08:43:25 GMT</pubDate>
            <atom:updated>2019-04-15T08:43:25.788Z</atom:updated>
            <content:encoded><![CDATA[<p>Using SonarLint in IntelliJ or your preferred IDE</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ySLpkUab2w-hxSds7wIrxA.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/photos/Fi-GJaLRGKc?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Pankaj Patel</a> on <a href="https://unsplash.com/search/photos/code-programming?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><p>In Javascript, you can so many linters from jslint to jshint and eslint. In Java, we also have linters. An example is SonarLint.</p><p>SonarLint is a plugin that can be installed into your IDE of your choice. At time of writing this tutorial. It is supported in IntelliJ IDEA and eclipse IDE.</p><p><strong>Purpose of Linting</strong></p><p>Linters are tools that you can use to help you debug your code. They scan your scripts for common issues and errors, and give you back a report with line numbers that you can use to fix things.</p><p>Besides, linters also check if your code adheres to standards, is it performance-oriented? Would there be any memory leak because you forgot to close a stream? Linters do this out of the box. You could also picture linter as your personal code reviewer. Besides, checking adherence to standards, linters help in identifying quality issues in your Java code.</p><p>According to the official docs,</p><blockquote>SonarLint is an IDE extension that helps you detect and fix quality issues as you write code. Like a spell checker, SonarLint squiggles flaws so they can be fixed before committing code. You can get it directly from the IntelliJ IDEA Plugin Repository, and it will then detect new bugs and quality issues as you code (Java, Kotlin, Ruby, JavaScript, PHP and Python).<br>If your project is analyzed on SonarQube or on SonarCloud, SonarLint can connect to the server to retrieve the appropriate quality profiles and settings for that project. Java 8 is required to run SonarLint.</blockquote><h3>How to install SonarLint?</h3><p>Java 8 is required to run SonarLint plugin.</p><ol><li>In your file menu, click on preferences. A dialog must be opened now.</li><li>In the left pane, click on plugins.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OB3F7tnGoRFQRQOwZ25VTw.png" /></figure><p>3. Search for SonarLint and click the green button with text Install.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SNdJVN9_qgPwDlCGxvS9kw.png" /></figure><p>It will require that you restart your IDE so do that now.</p><h3>Let’s analyze our code</h3><p>Right click on the file or package you want to scan, then look for analyze and analyze with Sonarlint.</p><p>After this, you should see the result open at the bottom of your IDE where Terminal, Version Control and Todo labels are.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PhND5gCASPTU-JflF_xSUg.png" /></figure><p>There is an issue with our code. I have clicked on the issue to see the message in the rule pane on the right hand side. The message is “Methods should not be empty.”</p><p>Let’s fix our code by adding a comment. See the fixed code below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*h0tcbklpsCLNn9QG1ub_KA.png" /></figure><p>We have added a block comment with text: We are doing nothing. After that, we re-scan our code and the issues have gone.</p><p>That wraps up out guide.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f175b6095ecb" width="1" height="1" alt=""><hr><p><a href="https://medium.com/zero-to-production/supercharge-your-code-quality-using-sonarlint-f175b6095ecb">Supercharge your code quality using SonarLint</a> was originally published in <a href="https://medium.com/zero-to-production">Zero To Production</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Create and publish your Rest API using Spring Boot and Heroku (Part 2)]]></title>
            <link>https://medium.com/zero-to-production/create-and-publish-your-rest-api-using-spring-boot-and-heroku-part-2-4c066696bab4?source=rss-e6e4f6ff5fad------2</link>
            <guid isPermaLink="false">https://medium.com/p/4c066696bab4</guid>
            <category><![CDATA[spring-training]]></category>
            <category><![CDATA[rest-api]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[spring-boot]]></category>
            <category><![CDATA[spring-boot-2]]></category>
            <dc:creator><![CDATA[Paul ‘Tofunmi O.]]></dc:creator>
            <pubDate>Thu, 28 Mar 2019 22:57:14 GMT</pubDate>
            <atom:updated>2019-04-01T14:34:51.366Z</atom:updated>
            <content:encoded><![CDATA[<p>Build and deploy RESTful API to Heroku</p><p>In <a href="https://medium.com/zero-to-production/create-and-publishing-your-rest-api-using-spring-boot-33aae4f10339">part one</a> of the Rest API using Spring Boot and Heroku, we built an imaginary bucket list of places we wish to travel to or visit in our lifetime. However, the buckets are not stored in a database. This means that whenever we restart our server our buckets information get lost.</p><p>Let’s fix that.</p><p>In part two of this tutorial, you will learn how to store our bucket lists in MySQL database and deploy it to Heroku.</p><p>To get the finished code, scroll down to the bottom of this page. If you are don’t know what Rest is or want a refresher on what we have covered so far, please read part 1 of the tutorial here.</p><p><strong>Tools used in the tutorial</strong></p><ol><li><strong>IDE:</strong> IntelliJ</li><li><strong>Framework:</strong> Spring Boot</li><li><strong>Dependency</strong>: Spring boot starter web</li></ol><ul><li>Web: It provides with tomcat server which handles request and response mapping among other things.</li><li>Mysql: This provides a connector for connect to mysql database</li><li>JPA: This is the ORM, Hibernate to be precise. It provides a wrapper for mapping Java classes to tables in the database.</li></ul><p><strong>4. Build Tool:</strong> Maven</p><p><strong>5. Language:</strong> Java</p><p><strong>6. Hosting platform:</strong> Heroku</p><p>7. <strong>Database:</strong> Mysql</p><p>8. <strong>Database GUI: </strong>Sequel Pro. You can use any tool of your choice.</p><p>This tutorial will be divided into two sections: section 1 and section 2. In section 1, we will be using the <a href="http://start.spring.io/">start.spring.io</a> to specify the dependencies we need and generate the boilerplate code. In the latter section, we will write the code.</p><h3>Section 1 (Pictures has been attached showing my selection)</h3><ol><li>Head over to <a href="https://start.spring.io/">start.spring.io</a> and provide the group and artifact name for your app. It is a Maven project written in Java 8.</li><li>The dependencies are Mysql, JPA and Web.</li><li>The group Id is com.zerotoproduction. Yours can be anything.</li><li>The artifact id is bucketlist.</li><li>Click on generate project</li><li>Extract to your computer and import the downloaded maven project to your favourite Editor</li><li>Open extracted folder in your editor.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/955/1*w17Mgb_34zW-o1HXY8ZTbg.png" /><figcaption>My selection on start.spring.io</figcaption></figure><p>My dependencies</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/375/1*GzXgjOngiyXWBmAaETk_XA.png" /><figcaption>dependencies for this project</figcaption></figure><h3>Section 2</h3><p>We need to create two Java classes. One will serve as a controller for receiving request and responding with response. The second will serve as a data model.</p><p>Here is what our Data Model(BucketList) looks like:</p><pre>package com.zerotoproduction.bucketlist;<br><br>import javax.persistence.*;<br><br>@Entity<br>public class BucketList {<br><br>    @Id<br>    @Column(name = &quot;id&quot;, unique = true, nullable = false)<br>    @GeneratedValue(strategy = GenerationType.<em>IDENTITY</em>)<br>    private long id;<br><br>    @Column(name = &quot;name&quot;, length = 60, nullable = false)<br>    private String name;<br><br>    @Column<br>    private  String description;<br><br>    BucketList() {<br><br>    }<br><br>    BucketList(String name, String description){<br>        this.name = name;<br>        this.description = description;<br>    }<br><br>    BucketList(long id, String name, String description){<br>        this.id = id;<br>        this.name = name;<br>        this.description = description;<br>    }<br><br>    public long getId() {<br>        return id;<br>    }<br><br>    public void setId(long id) {<br>        this.id = id;<br>    }<br><br>    public String getName() {<br>        return name;<br>    }<br><br>    public void setName(String name) {<br>        this.name = name;<br>    }<br><br>    public String getDescription() {<br>        return description;<br>    }<br><br>    public void setDescription(String description) {<br>        this.description = description;<br>    }<br><br>    @Override<br>    public String toString() {<br>        return &quot;BucketList{&quot; +<br>                &quot;id=&quot; + id +<br>                &quot;, name=&#39;&quot; + name + &#39;\&#39;&#39; +<br>                &quot;, description=&#39;&quot; + description + &#39;\&#39;&#39; +<br>                &#39;}&#39;;<br>    }<br>}</pre><p>An explanation for each of the annotation</p><p>1. @Entity: with this annotation, we have specified that this class represents an entity in the DB.</p><p>2. @Id: this specifies that this attribute is a primary key</p><p>3. @Column(name = “id”, unique = true, nullable = false): @Column specifies that this field should be column, its name should be id, the values should be unique and it cannot be null.</p><p>4. @GeneratedValue(strategy = GenerationType.IDENTITY). We are specified that the values should be generated by DB using Identity generation type.</p><p>We also need Data Access Object (DAO). Luckily for us, Spring comes with lots of options from CrudRepository to JPARepository. These interfaces provide CRUD functionalities out of the box for Objects annotated with @Entity annotation. However, the caveat is that your DAO interface must extend them and specify the entity and data type of the primary key for that entity. In our example, we are extending JPARepository like so: JpaRepository&lt;BucketList, Long&gt;. The entity is BucketList and data type of its primary key is Long. Now we have all we need to persist our buckets in the DB.</p><p>Here is what our BucketListRepository looks like</p><pre>package com.zerotoproduction.bucketlist;<br><br>import org.springframework.data.jpa.repository.JpaRepository;<br><br>public interface BucketRepository extends JpaRepository&lt;BucketList, Long&gt; {<br>}</pre><p>Here is what the controller looks like:</p><pre>package com.zerotoproduction.bucketlist;<br><br>import org.springframework.beans.factory.annotation.Autowired;<br>import org.springframework.http.ResponseEntity;<br>import org.springframework.web.bind.annotation.*;<br>import java.util.Optional;<br><br>@RestController<br>public class BucketListController {<br><br>    @Autowired<br>    BucketRepository bucketRepository;<br><br>    @GetMapping(value = &quot;/&quot;)<br>    public ResponseEntity index() {<br>        return ResponseEntity.<em>ok</em>(bucketRepository.findAll());<br>    }<br><br>    @GetMapping(value = &quot;/bucket&quot;)<br>    public ResponseEntity getBucket(@RequestParam(value=&quot;id&quot;) Long id) {<br>        Optional&lt;BucketList&gt; foundBucketList = bucketRepository.findById(id);<br><br>        if(foundBucketList.isPresent()){<br>            return ResponseEntity.<em>ok</em>(foundBucketList.get());<br>        }else {<br>            return ResponseEntity.<em>badRequest</em>().body(&quot;No bucket with specified id &quot; + id + &quot; found&quot;);<br>        }<br>    }<br><br>    @PostMapping(value = &quot;/&quot;)<br>    public ResponseEntity addToBucketList(@RequestParam(value=&quot;name&quot;) String name, @RequestParam(value=&quot;description&quot;) String desc) {<br>        return ResponseEntity.<em>ok</em>(bucketRepository.save(new BucketList(name, desc)));<br>    }<br><br>    @PutMapping(value = &quot;/&quot;)<br>    public ResponseEntity updateBucketList(@RequestParam(value=&quot;name&quot;) String name, @RequestParam(value=&quot;id&quot;) Long id, @RequestParam(value=&quot;description&quot;) String desc) {<br>        Optional&lt;BucketList&gt; optionalBucketList = bucketRepository.findById(id);<br>        if(!optionalBucketList.isPresent()){<br>            return ResponseEntity.<em>badRequest</em>().body(&quot;No bucket with specified id &quot; + id + &quot; found&quot;);<br>        }<br><br>        BucketList foundBucketList = optionalBucketList.get();<br>        foundBucketList.setName(name);<br>        foundBucketList.setDescription(desc);<br><br>        return ResponseEntity.<em>ok</em>(bucketRepository.save(foundBucketList));<br>    }<br><br>    @DeleteMapping(value = &quot;/&quot;)<br>    public ResponseEntity removeBucketList(@RequestParam(value=&quot;id&quot;) Long id) {<br>        bucketRepository.deleteById(id);<br>        return ResponseEntity.<em>noContent</em>().build();<br>    }<br>}</pre><p>Here is what my folder structure looks like</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/306/1*0KppgN1ZwRwCeQ6sK0s2UA.png" /><figcaption>Folder structure in IntelliJ</figcaption></figure><p>Since we are connecting to a database, we need the address of the database, username and password.</p><p>We will test this locally on our pc before deploying it to Heroku. I have specified the properties in application.properties. Let’s go over it</p><pre>spring.datasource.url=jdbc:mysql://localhost:3306/zero_to_production_bucketlist_jpa?serverTimezone=UTC<br>spring.datasource.username=root<br>spring.datasource.password=Toor1234<br><br># Hibernate ddl auto (create, create-drop, update)<br>spring.jpa.hibernate.ddl-auto=update<br><br>#MySQL DIALECT<br>#spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.MySQL5Dialect<br><br>server.port=9009</pre><ol><li>spring.datasource.url specifies the connection string for connecting to the database</li><li>spring.datasource.username specifies the username for connecting to the Db</li><li>spring.datatsource.password specifies the password.</li><li>spring.jpa.hibernate.ddl-auto specifies how hibernate will handle entities in your database. The create option means that all entities will be dropped and created at every restart while the update option adds changes to the entities without dropping it. In production, you need to use update else your data will be flushed.</li><li>server.port specifies the port number our application will run on.</li></ol><p>It’s time to test and we will do it this time locally. We will use Postman</p><p><strong>Test 1: Add a bucket list</strong></p><p>http://localhost:9009?name=Visit Big Ben&amp;description=My first list</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/996/1*H7OzLP2erz5Mt0eGF2JFnw.png" /><figcaption>Add a bucket list</figcaption></figure><p><strong>Test 2: Get all bucket lists</strong></p><p>http://localhost:9009</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/998/1*7zAFa2PvEPJps1GxdDbE5A.png" /><figcaption>Get all bucket list</figcaption></figure><p><strong>Test 3: get single bucket list</strong></p><p><a href="http://localhost:9009/bucket?id=1">http://localhost:9009/bucket?id=1</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1002/1*EsTN3uen_PxSfmzMhXGtHQ.png" /></figure><p><strong>Test 4: Update Bucket</strong></p><p>http://localhost:9009?name=Visit Big Ben Updated&amp;description=My first list&amp;id=1</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/993/1*MmW27rXn9--TmoV2cVD7NQ.png" /></figure><p><strong>Test 5: Delete bucket</strong></p><p><a href="http://localhost:9009/?id=2">http://localhost:9009?id=2</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*o3ZrriYb6R2zxRQ5T_MbrQ.png" /></figure><p>Let’s deploy to Heroku</p><p>We need to use ClearDB Mysql Addon on Heroku</p><p>First, we prepare the Spring Boot for heroku like so:</p><ul><li><strong>git init</strong> to initialise the repository</li><li><strong>git add . </strong>to add all files in folder</li><li><strong>git commit -m ‘Commit name’: </strong>commit changes</li><li><strong>heroku create: </strong>to create heroku app</li></ul><p>Next, you need to add mysql DB like so:</p><pre>heroku addons:create cleardb:ignite</pre><p>Now that you have add clearDB, you need the connection url. To get this, type like so:</p><pre>heroku config</pre><p>It should return your connection string.</p><p>You need to replace the spring.datasource.url value with the value return from heroku config.</p><p>One last thing though, to make it work, add a database config file like so:</p><pre>package com.zerotoproduction.bucketlist;<br><br>import com.zaxxer.hikari.HikariConfig;<br>import com.zaxxer.hikari.HikariDataSource;<br>import org.springframework.beans.factory.annotation.Value;<br>import org.springframework.context.annotation.Bean;<br>import org.springframework.context.annotation.Configuration;<br><br>import javax.sql.DataSource;<br><br>@Configuration<br>public class DatabaseConfig {<br><br>    @Value(&quot;${spring.datasource.url}&quot;)<br>    private String dbUrl;<br><br>    @Bean<br>    public DataSource dataSource() {<br>        HikariConfig config = new HikariConfig();<br>        config.setJdbcUrl(dbUrl);<br>        return new HikariDataSource(config);<br>    }<br>}</pre><p>It’s time to deploy to heroku</p><pre>git push heroku master</pre><p>At the end of this process, you should have your app deployed to Heroku</p><p>To test, you remove the localhost and port number. For example to get all bucketlists on a deployed app, the url is like this:</p><pre><a href="https://tranquil-mountain-81706.herokuapp.com/">https://tranquil-mountain-81706.herokuapp.com/</a></pre><p>Just repeat the same process we followed for testing locally however you should remove localhost and port</p><p>That marks the end of this step 2. <br>In step 3, I plan to introduce authentication and roles using Spring Security. In step 4, we would consume the rest api using a JS library like VueJS or React JS.</p><p>Stay tuned</p><p>Share, clap and add your comment.</p><p>The complete code can be found here:</p><p><a href="https://github.com/zero-to-production/bucketlist">https://github.com/zero-to-production/bucketlist</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4c066696bab4" width="1" height="1" alt=""><hr><p><a href="https://medium.com/zero-to-production/create-and-publish-your-rest-api-using-spring-boot-and-heroku-part-2-4c066696bab4">Create and publish your Rest API using Spring Boot and Heroku (Part 2)</a> was originally published in <a href="https://medium.com/zero-to-production">Zero To Production</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Create and publishing your Rest API using Spring Boot]]></title>
            <link>https://medium.com/zero-to-production/create-and-publishing-your-rest-api-using-spring-boot-33aae4f10339?source=rss-e6e4f6ff5fad------2</link>
            <guid isPermaLink="false">https://medium.com/p/33aae4f10339</guid>
            <category><![CDATA[spring-boot-deployment]]></category>
            <category><![CDATA[spring-boot]]></category>
            <dc:creator><![CDATA[Paul ‘Tofunmi O.]]></dc:creator>
            <pubDate>Fri, 15 Mar 2019 12:20:20 GMT</pubDate>
            <atom:updated>2019-03-29T09:31:05.214Z</atom:updated>
            <content:encoded><![CDATA[<h3>Create and publish your Rest API using Spring Boot and Heroku (Part 1)</h3><p>Build and deploy RESTful API to Heroku</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5JTH58x775NGDTAOsgLRLA.jpeg" /><figcaption>Photo by<a href="https://unsplash.com/photos/P2SkP_PXhlU?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText"> Fabian Grohs</a> on<a href="https://unsplash.com/search/photos/programming?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText"> Unsplash</a></figcaption></figure><p>In this tutorial, you will learn how to use Spring Boot to develop RESTful API and publish your API to Heroku. First, we will build the api; upon completion, we will deploy to Heroku.</p><p><strong>Introduction to REST</strong></p><p>RESTful API or web service is an application programming interface using HTTP request types: GET, POST, DELETE and PUT to perform actions on data. It is generally preferred to its closest alternative Simple Object Access Protocol (SOAP) because it requires less resources. By writing APIs that adhere to RESTful practices, you are agreeing to adopt an architectural style of representing, requesting, storing data and deleting data.</p><p><strong>GET:</strong> It is used for requesting data. You can request for a single item or list of items</p><p><strong>PUT: </strong>It is used for updating an item.</p><p><strong>POST: </strong>It is used for creating an item</p><p><strong>DELETE: </strong>It is used for deleting an item.</p><p><strong>Tools used in the tutorial</strong></p><ul><li>IDE: IntelliJ</li><li>Framework: Spring Boot</li><li>Dependency: Spring boot starter web</li><li>Build Tool: Maven</li><li>Language: Java</li><li>Hosting platform: Heroku</li></ul><p>The Spring boot starter web contains everything needed to bootstrap an app such as an embedded server. Tomcat is the default.</p><p>If you don’t have a <a href="http://heroku.com/">Heroku</a> account, you may sign up using this <a href="https://signup.heroku.com/">link</a></p><p><strong>What are we building?</strong></p><p>Imagine we have a bucket list of places we wish to travel to or visit in our lifetime. I hope you do. We would create an app for adding, editing, viewing and deleting items in our bucket list. In this tutorial, we will be using a non-persistent DB (ArrayList); if you want a persistent store, comment below as we have another tutorial for that.</p><p><strong>Section 1</strong></p><ol><li>Head over to <a href="https://start.spring.io/">start.spring.io</a> and provide the group and artifact name for your app. It is a Maven project written in Java and the dependency is Web.</li><li>The only dependency needed is the Web dependency.</li><li>Click on generate project</li><li>Extract to your computer and import the downloaded maven project to your favourite Editor</li><li>Open extracted folder in your editor.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ApR3E0oOEFLVHrD1cw72uQ.png" /></figure><p><strong>Time to write some code</strong></p><p>We need to create two Java classes. One will serve as a controller for receiving request and responding with response. The second will serve as a data model.</p><p>Data Model(BucketList)</p><pre>package com.zerotoproduction.firstrest;<br><br>public class BucketList {<br><br>    private long id;<br>    private String name;<br><br>    BucketList(long id, String name){<br>        this.id = id;<br>        this.name = name;<br>    }<br><br>    public long getId() {<br>        return id;<br>    }<br><br>    public void setId(long id) {<br>        this.id = id;<br>    }<br><br>    public String getName() {<br>        return name;<br>    }<br><br>    public void setName(String name) {<br>        this.name = name;<br>    }<br>}</pre><p>Controller(BucketListController)</p><pre>package com.zerotoproduction.firstrest;<br><br>import org.springframework.http.ResponseEntity;<br>import org.springframework.web.bind.annotation.*;<br><br>import java.util.ArrayList;<br>import java.util.List;<br>import java.util.concurrent.atomic.AtomicLong;<br><br>@RestController<br>public class BucketListController {<br><br>    private List&lt;BucketList&gt; myBucketList = new ArrayList();<br>    private final AtomicLong counter = new AtomicLong();<br><br>    public BucketListController(){<br>        myBucketList.add(new BucketList(counter.incrementAndGet(), &quot;Visit Colosseum in Rome&quot;));<br>    }<br><br>    @GetMapping(value = &quot;/&quot;)<br>    public ResponseEntity index() {<br>        return ResponseEntity.<em>ok</em>(myBucketList);<br>    }<br><br>    @GetMapping(value = &quot;/bucket&quot;)<br>    public ResponseEntity getBucket(@RequestParam(value=&quot;id&quot;) Long id) {<br>        BucketList itemToReturn = null;<br>        for(BucketList bucket : myBucketList){<br>            if(bucket.getId() == id)<br>                itemToReturn = bucket;<br>        }<br><br>        return ResponseEntity.<em>ok</em>(itemToReturn);<br>    }<br><br>    @PostMapping(value = &quot;/&quot;)<br>    public ResponseEntity addToBucketList(@RequestParam(value=&quot;name&quot;) String name) {<br>        myBucketList.add(new BucketList(counter.incrementAndGet(), name));<br>        return ResponseEntity.<em>ok</em>(myBucketList);<br>    }<br><br>    @PutMapping(value = &quot;/&quot;)<br>    public ResponseEntity updateBucketList(@RequestParam(value=&quot;name&quot;) String name, @RequestParam(value=&quot;id&quot;) Long id) {<br>        myBucketList.forEach(bucketList -&gt;  {<br>            if(bucketList.getId() == id){<br>                bucketList.setName(name);<br>            }<br>        });<br>        return ResponseEntity.<em>ok</em>(myBucketList);<br>    }<br><br>    @DeleteMapping(value = &quot;/&quot;)<br>    public ResponseEntity removeBucketList(@RequestParam(value=&quot;id&quot;) Long id) {<br>        BucketList itemToRemove = null;<br>        for(BucketList bucket : myBucketList){<br>            if(bucket.getId() == id)<br>                itemToRemove = bucket;<br>        }<br><br>        myBucketList.remove(itemToRemove);<br>        return ResponseEntity.<em>ok</em>(myBucketList);<br>    }<br>}</pre><p>As an addendum, although it is not required, you can specify a port for running your apps. If you do not specify a port, it uses port 8080 by default. I have specified my port to be 9009 in the application properties file like so:</p><pre>server.port=9009</pre><p><strong>Let us test our apis locally using Postman</strong></p><ol><li>To get all items in bucketlist, I am using this url like so:</li></ol><pre>localhost:9009</pre><p>You ought to change the port number to what you have specified locally.</p><p>You should see a response similar to the one below</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1006/1*fUusHV67niP3bwgKY-Rxqg.png" /></figure><p>2. To add an item, we specify the name in the url like so:</p><pre>localhost:9009?name=Visit Big Ben</pre><p>We have added “Visit Big Ben”</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1010/1*f9brBmXnj5iH90fSwtfEIA.png" /></figure><p>3. To view a single item in bucket list</p><pre>localhost:9009/bucket?id=2</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1012/1*HxupoM1hxrBg8czvDOuX4g.png" /></figure><p>4. To edit an item, we specify the id and new name in the url like so:</p><pre>localhost:9009?id=2&amp;name=Visit Kensington Palace</pre><p>We just changed name of the second item in our bucket list from visit big ben to Visit Kensington Palace.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1015/1*fSDm5UE5rI3hT794OyhTQg.png" /></figure><p>5. To remove an item, we specify the id</p><pre>localhost:9009?id=2</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1014/1*a8zdZQCGtd2vaZAbNbCzZw.png" /></figure><p><strong>Section 2: Time to deploy to Heroku</strong></p><ol><li>You need to create an account on <a href="http://heroku.com/">Heroku</a></li><li>Install Heroku Cli. Heroku CLI is a command line application that lets you create, deploy and manage Heroku apps from the command line. You can download Heroku CLI from <a href="https://devcenter.heroku.com/articles/heroku-cli#download-and-install">Heroku Dev Center</a>.</li><li>Login using your email and password</li></ol><pre>heroku login</pre><p>4. Set up Git and create a Heroku app</p><pre>git init<br>git add .<br>git commit -m &quot;initial commit&quot;</pre><p>5. Now, create an app using heroku create like so</p><pre>heroku create</pre><p>6. Deploy app to Heroku</p><pre>git push heroku master</pre><p>7. Our app has been deployed to Heroku now</p><pre><a href="https://intense-sands-41425.herokuapp.com/">https://intense-sands-41425.herokuapp.com/</a></pre><p>Let’s test again but you must remove the localhost and port with the url given by heroku.</p><p>For example, to get all items in our bucket list, we use</p><pre><a href="https://intense-sands-41425.herokuapp.com/">https://intense-sands-41425.herokuapp.com/</a></pre><p>and to get an item we use</p><pre><a href="https://intense-sands-41425.herokuapp.com/bucket?id=1">https://intense-sands-41425.herokuapp.com/bucket?id=1</a></pre><p>That wraps up our tutorial today.</p><p>Leave your comments, reviews, recommendations in the comment section. If you want to learn how to deploy PostgreSQL and Mysql Spring Boot to Heroku, let me know in the comment section below.</p><p>Email: zerotoproduction@gmail.com</p><p>Github: <a href="https://github.com/zero-to-production/firstrest">https://github.com/zero-to-production/firstrest</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=33aae4f10339" width="1" height="1" alt=""><hr><p><a href="https://medium.com/zero-to-production/create-and-publishing-your-rest-api-using-spring-boot-33aae4f10339">Create and publishing your Rest API using Spring Boot</a> was originally published in <a href="https://medium.com/zero-to-production">Zero To Production</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Spring Framework Series]]></title>
            <link>https://medium.com/zero-to-production/spring-framework-series-4554c92a69b?source=rss-e6e4f6ff5fad------2</link>
            <guid isPermaLink="false">https://medium.com/p/4554c92a69b</guid>
            <category><![CDATA[spring-complete-tutorial]]></category>
            <category><![CDATA[spring-boot]]></category>
            <category><![CDATA[spring-framework]]></category>
            <dc:creator><![CDATA[Paul ‘Tofunmi O.]]></dc:creator>
            <pubDate>Fri, 15 Mar 2019 10:16:38 GMT</pubDate>
            <atom:updated>2019-03-30T08:35:46.776Z</atom:updated>
            <content:encoded><![CDATA[<h3>Spring Framework Series: Zero to Hero</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9my22RFVDigz0GlZps1ufQ.jpeg" /><figcaption><a href="https://www.pexels.com/photo/hello-spring-handwritten-paper-920147/">Source: https://www.pexels.com/photo/hello-spring-handwritten-paper-920147/</a></figcaption></figure><p>In this series, I will cover projects in the Spring Framework(write code, deploy and publish to a public repository). We will It is intended for programmers at all levels.</p><p><strong>Purpose of this guide.</strong></p><p>This guide provides an introduction to the Java Spring framework, explains the modules of this framework and provides examples of each of these modules. The intention of the author is create a go-to (pocket reference) guide for developers at all levels.</p><p><strong>My Objective</strong></p><p>I am doing this series to give back to the community in 2019. Using this medium (no pun intended), I will be documenting my experiences and sharing my knowledge with the rest of the world.</p><p>The series is made up of many parts, it is expected that you read this guide before moving to the different parts. The link to the different parts is at the bottom of this guide.</p><p><strong>Intended Audience</strong></p><p>It is expected that you have solid grasp of Java programming language especially Java SE edition.</p><p><strong>What is Spring Framework?</strong></p><p>Spring Framework is an open source application framework and and inversion of control container for Java. The framework introduces core features required in any Java application. It also provides extensions, modules and starter packs focusing on “plumbing” of enterprise applications so that teams can focus on business logic. Over the years, it has grown from being just an IOC container to including several modules for building different parts of an application. These modules include authentication and authorization, transaction management, data access, messaging and testing.</p><p><strong>Spring Container</strong></p><p>In the world of Java EE, there are containers such as web or servlet containers for managing servlets, filters, JSPs etc .and EJB container for managing EJB components such as entity beans, session and message driven beans. The Spring container not only handles the creation and management of components; it provides services to these components managed in its containers. These servers include transaction management, persistence, security and messaging.</p><p><strong>Spring Framework Projects/modules</strong></p><p>As the Spring Framework continues to evolve, we expect to see more projects. You can see the full list of projects here<a href="https://spring.io/projects/spring-framework"> https://spring.io/projects/spring-framework</a>. In this guide, in no particular order, we will cover the following projects:</p><ol><li><strong>Spring Boot</strong></li></ol><p>Spring Boot is designed to get you up and running as quickly as possible, with minimal upfront configuration of Spring. In this <a href="https://medium.com/zero-to-production/create-and-publishing-your-rest-api-using-spring-boot-33aae4f10339">guide, we used Spring Boot to create your first REST API</a>. It takes an opinionated view of building production-ready applications. Spring Boot comes with several starter options to simplify and reduce development time.</p><p><strong>2. Spring Security</strong></p><p>The security module of Spring Framework placed it miles ahead of its competitors. Spring Security provides customized yet powerful authentication and access control mechanism for application. Depending on your requirements, you can use one single or multiple authentication types in your spring applications. We will be looking at Spring Security using JWT, building an authorization and resource server and protecting resources using roles and permissions.</p><p><strong>3. Spring Batch </strong>provides tooling features for development of batch applications. These reusable features helps in processing large volumes data, manage resource management, transaction management, tracing and logging etc.</p><p><strong>4. Spring Hateoas</strong> solves the problem of creating RESTful representation that follow the HATEAOS principle when working with Spring.</p><p><strong>5. Spring Data</strong></p><p>Spring Data provides a programming model for data access while still retaining the special traits of the underlying data store. It makes it so easy to access database technologies from relational datastore to non-relational, cloud-based and map-reduce data serves. This project has many modules which we will provide sample tutorial in this guide. Some of the exciting modules in this project are: Spring Data JDBC — provides Spring data repository for JDBC, <a href="https://medium.com/zero-to-production/create-and-publish-your-rest-api-using-spring-boot-and-heroku-part-2-4c066696bab4">Spring Data JPA — provides support for JPA such as Hibernate (this tutorial on zero to production uses JPA)</a> and its alternatives and Spring Data MongoDB — provides object-document repository for MongoDB.</p><p>We would cover these projects, modules and many more in the coming weeks.</p><p>Leave a comment, share, leave reviews and recommendations.</p><p>Let’s get started.</p><p><strong>Spring Series Table of Contents</strong></p><p>Part 1: <a href="https://medium.com/zero-to-production/create-and-publishing-your-rest-api-using-spring-boot-33aae4f10339?source=collection_home---4------1---------------------">Create your first restful api</a></p><p><a href="https://medium.com/zero-to-production/create-and-publish-your-rest-api-using-spring-boot-and-heroku-part-2-4c066696bab4?source=collection_home---4------0---------------------">Part 2: Next, is using Spring Data JPA</a></p><p>Part 3: Using Spring Security (Authorization and Authentication) using a secret signing key, JWT, Roles (Coming Soon).</p><p>Part 4: Using Spring Security (Authorization and Authentication) using JWT, Oauth 2.0 and Roles. We will build Authorisation and Resource Server using public and private keys.</p><p>Part 5: Building the frontend using VueJS</p><p>Part 6: Building the frontend using ReactJS</p><p>To get latest updates on follow us on twitter and github</p><p><a href="https://twitter.com/zerotoprod">zerotoproduction (@zerotoprod) | Twitter</a></p><p>Github: <a href="https://github.com/zero-to-production">https://github.com/zero-to-production</a></p><p>Email: zerotoproduction@gmail.com</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4554c92a69b" width="1" height="1" alt=""><hr><p><a href="https://medium.com/zero-to-production/spring-framework-series-4554c92a69b">Spring Framework Series</a> was originally published in <a href="https://medium.com/zero-to-production">Zero To Production</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Spring Boot Series]]></title>
            <link>https://medium.com/series/spring-boot-series-590884a83eda?source=rss-e6e4f6ff5fad------2</link>
            <guid isPermaLink="false">https://medium.com/p/590884a83eda</guid>
            <dc:creator><![CDATA[Paul ‘Tofunmi O.]]></dc:creator>
            <pubDate>Fri, 15 Mar 2019 09:47:05 GMT</pubDate>
            <atom:updated>2019-03-15T09:47:05.777Z</atom:updated>
            <content:encoded><![CDATA[<p><strong>Purpose of this guide.</strong></p><p>This guide provides an introduction to the Java Spring framework, explains the modules of this framework and provides examples of each of these modules. The intention of the author is create a go-to (pocket reference) guide for developers at all levels.</p><p><strong>Intended Audience</strong></p><p>It is expected that you have solid grasp of Java programming language especially Java SE edition.</p><p><strong>What is Spring Framework?</strong></p><p>Spring Framework is an open source application framework and and inversion of control container for Java. The framework introduces core features required in any Java application. It also provides extensions, modules and starter packs focusing on “plumbing” of enterprise applications so that teams can focus on business logic. Over the years, it has grown from being just an IOC container to including several modules for building different parts of an application. These modules include authentication and authorization, transaction management, data access, messaging and testing.</p><p><strong>Spring Container</strong></p><p>In the world of Java EE, there are containers such as web or servlet containers for managing servlets, filters, JSPs etc .and EJB container for managing EJB components such as entity beans, session and message driven beans. The Spring container not only handles the creation and management of components; it provides services to these components managed in its containers. These servers include transaction management, persistence, security and messaging.</p><p>Spring Framework Projects/modules</p><p>As the Spring Framework continues to evolve, we expect to see more projects. You can see the full list of projects here <a href="https://spring.io/projects/spring-framework">https://spring.io/projects/spring-framework</a>. In this guide, in no particular order, we will cover the following projects:</p><p><strong>Spring Boot</strong></p><p>Spring Boot is designed to get you up and running as quickly as possible, with minimal upfront configuration of Spring. In this guide, we will use Spring Boot to create your first REST API. It takes an opinionated view of building production-ready applications. Spring Boot comes with several starter options to simplify and reduce development time.</p><p><strong>Spring Security</strong></p><p>The security module of Spring Framework placed it miles ahead of its competitors. Spring Security provides customized yet powerful authentication and access control mechanism for application. Depending on your requirements, you can use one single or multiple authentication types in your spring applications. We will be looking at Spring Security using JWT, building an authorization and resource server and protecting resources using roles and permissions.</p><p><strong>Spring Batch </strong>provides tooling features for development of batch applications. These reusable features helps in processing large volumes data, manage resource management, transaction management, tracing and logging etc.</p><p><strong>Spring Hateoas</strong> solves the problem of creating RESTful representation that follow the HATEAOS principle when working with Spring.</p><p><strong>Spring Data</strong></p><p>Spring Data provides a programming model for data access while still retaining the special traits of the underlying data store. It makes it so easy to access database technologies from relational datastore to non-relational, cloud-based and map-reduce data serves. This project has many modules which we will provide sample tutorial in this guide. Some of the exciting modules in this projects are:</p><ul><li>Spring Data JDBC provides Spring data repository for JDBC</li><li>Spring Data JPA provides support for JPA such as Hibernate and its alternatives.</li><li>Spring Data MongoDB provides object-document repository for MongoDB.</li></ul><p>In the coming weeks, we look at each of these modules, code sample applications,deploy them and make code available on a public repository.</p><p>Happy reading and participation</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=590884a83eda" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Deploying your Spring boot to Heroku]]></title>
            <link>https://medium.com/zero-to-production/deploying-your-spring-boot-to-heroku-f27044e9beca?source=rss-e6e4f6ff5fad------2</link>
            <guid isPermaLink="false">https://medium.com/p/f27044e9beca</guid>
            <category><![CDATA[spring-boot]]></category>
            <category><![CDATA[spring]]></category>
            <dc:creator><![CDATA[Paul ‘Tofunmi O.]]></dc:creator>
            <pubDate>Thu, 28 Feb 2019 14:31:06 GMT</pubDate>
            <atom:updated>2019-04-13T17:50:50.348Z</atom:updated>
            <content:encoded><![CDATA[<p>Learn how to deploy your app to heroku</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Z6Qs7rqBTnEJXyzZKbD-ig.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/photos/mxPiMiz7KCo?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Daniel Korpai</a> on <a href="https://unsplash.com/search/photos/server?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><p>We often develop software on our local machine but the real fun and fulfillment comes when it is available to a global audience. In this guide, you will learn how to deploy your Spring Boot app or any app to Heroku.</p><ol><li>Sign up on <a href="http://heroku.com/">Heroku here</a></li><li>Install Heroku Cli. Heroku CLI is a command line application that lets you create, deploy and manage Heroku apps from the command line. You can download Heroku CLI from <a href="https://devcenter.heroku.com/articles/heroku-cli#download-and-install">Heroku Dev Center</a>.</li><li>Login using your email and password like so:</li></ol><pre>heroku login</pre><p>4. Initialize git in your root folder like so:</p><pre>git init<br>git add .<br>git commit -m &quot;My first push to heroku&quot;</pre><p>5. Now, create an app using heroku create. This command creates an app and returns a name when it is done. You can do it like so:</p><pre>heroku create</pre><p>6. Deploy app to Heroku</p><pre>git push heroku master</pre><p>That’s it. You have your app deployed to Heroku.</p><p>That wraps up our tutorial today.</p><p>Leave your comments, reviews, recommendations in the comment section. If you want to learn how to develop web apps, rest apis, payment gateway, e-wallet using Java, please leave your comment in the comment section below.</p><h3><strong>What are we up to today?</strong></h3><p>We have a series on building rest api using spring boot. You can follow the guide here:</p><p><a href="https://medium.com/zero-to-production/spring-framework-series-4554c92a69b">https://medium.com/zero-to-production/spring-framework-series-4554c92a69b</a></p><p>Email: zerotoproduction@gmail.com</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f27044e9beca" width="1" height="1" alt=""><hr><p><a href="https://medium.com/zero-to-production/deploying-your-spring-boot-to-heroku-f27044e9beca">Deploying your Spring boot to Heroku</a> was originally published in <a href="https://medium.com/zero-to-production">Zero To Production</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[First Steps in Spring Boot]]></title>
            <link>https://medium.com/zero-to-production/first-steps-in-spring-boot-8320a487b87b?source=rss-e6e4f6ff5fad------2</link>
            <guid isPermaLink="false">https://medium.com/p/8320a487b87b</guid>
            <category><![CDATA[spring-boot]]></category>
            <category><![CDATA[spring-jpa]]></category>
            <category><![CDATA[spring]]></category>
            <category><![CDATA[spring-api]]></category>
            <category><![CDATA[spring-rest-mvc]]></category>
            <dc:creator><![CDATA[Paul ‘Tofunmi O.]]></dc:creator>
            <pubDate>Thu, 28 Feb 2019 11:44:02 GMT</pubDate>
            <atom:updated>2019-04-13T18:02:51.570Z</atom:updated>
            <content:encoded><![CDATA[<p>Learning Spring: What is Spring, how to learn Spring and deploying Spring application?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_XZk-_lcA1XNpP4mKqTICw.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/photos/C8NDn4xk9zs?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Dean Pugh</a> on <a href="https://unsplash.com/search/photos/java-development?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><p>In this series, I will cover projects in the Spring Framework(write code, deploy and publish to a public repository). We will It is intended for programmers at all levels.</p><p>You can view it here:</p><p><a href="https://medium.com/zero-to-production/spring-framework-series-4554c92a69b">https://medium.com/zero-to-production/spring-framework-series-4554c92a69b</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8320a487b87b" width="1" height="1" alt=""><hr><p><a href="https://medium.com/zero-to-production/first-steps-in-spring-boot-8320a487b87b">First Steps in Spring Boot</a> was originally published in <a href="https://medium.com/zero-to-production">Zero To Production</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[A Brief Explanation of Database abstraction Layer: Writing database queries for the future]]></title>
            <link>https://medium.com/@paultofunmi/a-brief-explanation-of-database-abstraction-layer-writing-database-queries-for-the-future-7a1c84c9a45d?source=rss-e6e4f6ff5fad------2</link>
            <guid isPermaLink="false">https://medium.com/p/7a1c84c9a45d</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[database-abstraction]]></category>
            <category><![CDATA[web-development]]></category>
            <dc:creator><![CDATA[Paul ‘Tofunmi O.]]></dc:creator>
            <pubDate>Mon, 23 Nov 2015 01:35:56 GMT</pubDate>
            <atom:updated>2015-11-23T01:35:56.226Z</atom:updated>
            <content:encoded><![CDATA[<p><strong>A Brief Explanation of Database abstraction Layer: Writing database queries for the future</strong></p><p><strong>In any new software project requiring persistent database storage, one question often comes up — how do we strive a balance between future complexity and current usability. As a developer, system analyst (or whatever your title is) you ought to consider a possibility that a database you use today, may be inappropriate somewhere in the future. If you really DON’T want to rewrite your code just to be able to use another database? If your answer is YES, then you are at the right place.</strong></p><p>Permit me to make a demarcation between three, often, confused terms — data access layer, database abstraction layer and data abstraction layer — and their functions. Merely knowing without knowledge of the applicability makes you not different from a neophyte.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/308/1*0v9bZrVg1aO62gbwl5HMcg.png" /></figure><p>To abstract is to reduce to the essential or general features. Abstraction, therefore, is the process of taking away or removing characteristics from something in order to reduce it to a set of essential characteristics. Database abstraction layers facilitate the design of flexible databases.</p><p>Let’s begin with database abstraction layer. They are programming interfacing (API) unifying the communication between an application and different databases eliminating the need to use different database vendors for each database. Simply said, it reduces the amount of work you as a developer need to do by making your database access codes work across multiple databases such as SQLite, SQLServer, DB2, MySQL, PostgreSQL and Oracle. Traditionally, if you had written your database queries to work with MySQL and 2 years down the line, your database changes to Oracle, you will need to rewrite most of your database queries.</p><p>Contrary to what most beginners tend to believe, data access layer don’t abstract the database. Instead, the make query building easier and, most times, a knowledge of the database structure is required to write queries.</p><p>For example, to write a query to retrieve the userId, firstName, lastName and dateJoined from the user table, the query would be like this:</p><blockquote>$Users-&gt;select(‘userId,firstName,lastName,dateJoined’)-&gt;where(‘userId&gt; 1’)-&gt;limit(1);</blockquote><p>Data access layer queries are similar to SQL and require knowledge of the database structure and a little bit of SQL.</p><p>Data abstraction layer (sometimes called Object-Relational Mappers) removes the need to understand the database structure or any knowledge of SQL.</p><p>The same SELECT query using ORM would look like this:</p><blockquote>Factory::find(‘Users’, 1)-&gt;filter(‘userId &gt; 0’);</blockquote><p>ORM makes database access more transparent so that you can easily map your objects to database tables (which require defining relationship between the tables). A simple query like the one above will update parent and child tables based on predefined relationship.</p><p><strong>Phase 2 (Delving into database abstraction layers)</strong></p><p>Let’s briefly look at the differences between database agnostic abstraction layers and database specific queries.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/280/1*eywcH3bnfP8u0J7gi6scuw.png" /></figure><p>Let’s look at the code for connecting to MySQL database</p><blockquote>STEP 1(Connect to the database server): $connection = mysqli_connect($host, $user, $password);</blockquote><blockquote>STEP 2(Connect to the database): $db = mysqli_select_db($database);</blockquote><p>Let’s look at the code for connecting to PostgreSQL database</p><blockquote>STEP 1 &amp; 2(Connect to the database): $connection = pg_connect(‘host=’. $host, ‘dbname=’. $database, ‘user=’ .$user, ‘password=’ .$password);</blockquote><p>However, if you write with Database abstraction layer, you only write your query once and it will work across multiple databases.</p><p>I have chosen <a href="http://phplens.com/lens/adodb/docs-adodb.htm#install">ADOdb Active Record</a> just for illustration purposes. It’s a PHP database class library that provides powerful abstractions for performing queries and managing databases. In addition, it hides the differences between the different databases so you can easily switch databases without changing the code. Besides, it can serve as a data abstraction layer and ORM in the form of ADOdb Active Record.</p><p>An example query with ADOdb is:</p><blockquote>//include adodb libraries</blockquote><blockquote>include_once(‘../adodb.inc.php’);</blockquote><blockquote>include_once(‘../adodb-active-record.inc.php’);</blockquote><blockquote>//specify your database driver e.g mysql, or postgreSQL</blockquote><blockquote>$db = ADONewConnection(‘mysql’);</blockquote><blockquote>//connect to the database</blockquote><blockquote>$db -&gt;Connect(‘localhost’, ‘root’, ‘pass’, ‘password’);</blockquote><blockquote>// Execute query</blockquote><blockquote>$rs = $db-&gt;Execute(‘select * from user’);</blockquote><p>Whenever you need to connect to a database, you create a Connection object using the ADONewConnection($driver) function or NewADOConnection($driver). After specifying the driver, the next thing is to connect to the database using the reference to the database connection obtained from ADONewConnection or NewADOConnection and execute your query.</p><h3><strong>Conclusion</strong></h3><p>Because of the need for a database class library that hides the differences between the different database API’s (encapsulate the differences) so it becomes easier to switch databases, database abstraction layer (ORM) was created. Other notable database abstraction layers are:</p><ol><li>Doctrine ORM</li><li>Eloquent ORM</li><li>Propel e.t.c.</li></ol><p>I hope this will help you make a choice…Go ORM. But for a start, try ADODB Active records, then move up the next level — ORM, PHP Frameworks e.t.c.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7a1c84c9a45d" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>