<?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[springboot-chronicles - Medium]]></title>
        <description><![CDATA[A Series of Spring Boot and Cloud Native tech how-tos from daily life - Medium]]></description>
        <link>https://medium.com/springboot-chronicles?source=rss----5d14c3ef5095---4</link>
        <image>
            <url>https://cdn-images-1.medium.com/proxy/1*TGH72Nnw24QL3iV9IOm4VA.png</url>
            <title>springboot-chronicles - Medium</title>
            <link>https://medium.com/springboot-chronicles?source=rss----5d14c3ef5095---4</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 29 Nov 2026 03:39:46 GMT</lastBuildDate>
        <atom:link href="https://medium.com/feed/springboot-chronicles" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[GraphQL in Springboot : A comparative study among the libraries and their implementation know-how]]></title>
            <link>https://medium.com/springboot-chronicles/graphql-in-springboot-a-comparative-study-among-the-libraries-and-their-implementation-know-how-b0e8d544f2fc?source=rss----5d14c3ef5095---4</link>
            <guid isPermaLink="false">https://medium.com/p/b0e8d544f2fc</guid>
            <category><![CDATA[java]]></category>
            <category><![CDATA[graphql]]></category>
            <category><![CDATA[graphql-java]]></category>
            <category><![CDATA[dgs-framework]]></category>
            <category><![CDATA[spring-boot]]></category>
            <dc:creator><![CDATA[Soham Dasgupta]]></dc:creator>
            <pubDate>Thu, 05 Aug 2021 19:16:05 GMT</pubDate>
            <atom:updated>2021-08-05T19:16:05.116Z</atom:updated>
            <content:encoded><![CDATA[<h3>GraphQL in Spring Boot : A comparative study among the libraries and their implementation know-how</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lpGItbr659SnsM6yZZ1gzg.png" /></figure><blockquote>GraphQL is a query language for APIs and a runtime for fulfilling those queries with your existing data. GraphQL provides a complete and understandable description of the data in your API, gives clients the power to ask for exactly what they need and nothing more, makes it easier to evolve APIs over time, and enables powerful developer tools.</blockquote><blockquote>From <a href="https://graphql.org/">https://graphql.org/</a></blockquote><p>It was introduced to “query what you need”. With traditional REST, the clients are bounded by the interface exposed, even though some attributes or objects are not needed, there is no way to filter that out. Also adds overhead to the server to fetch, aggregate and process that data before sending it back.</p><p>So Facebook designed it to get around common constraints in fetching data via REST and was open sourced in 2015.</p><p>Since then, a lot of development and innovation happened in the GraphQL space and specifically how to write such APIs in Java and Spring Boot.</p><p>In this blog, I will go through the available libraries we have, to implement GraphQL in Spring Boot and a comprehensive comparison on different aspects of these libraries.</p><h3>The Libraries</h3><p>There are 3 libraries to write GraphQL APIs in Spring Boot. All these libraries are active and back by a very enthusiastic community. Below are the details of these libraries as of August’21.</p><p><strong>graphql-java</strong></p><p>This it the recommended library listed in graphql.org. The oldest one to implement GraphQL in Java.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/675/1*WWR9ChWDcqZBekPaWB6yGA.png" /></figure><p>The current version is 17.0 and last released on Aug’21.</p><p>Documentation: <a href="https://www.graphql-java.com/">https://www.graphql-java.com/</a></p><p>Code: <a href="https://github.com/graphql-java">https://github.com/graphql-java</a></p><p>This library requires an extra dependency for Spring Boot. They also have a reactive version (instead of webmvc, it is webflux)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/681/1*c7OOUEeTgAKDEfZ1jsEIcA.png" /><figcaption>pom dependencies for graphql-java</figcaption></figure><p><strong>graphql-java-kickstart</strong></p><p>Introduced in 2018, this library has all you need for a Spring Boot application in one artifact. Originally was part of graphql-java but separated in a later stage.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/675/1*VAuXw99jXWCPebGpVYSDeA.png" /></figure><p>Current version is 11.1.0 and was last released on May’21</p><p>Documentation: <a href="https://graphql-java-kickstart.com/">https://graphql-java-kickstart.com/</a></p><p>Code: <a href="https://github.com/graphql-java-kickstart">https://github.com/graphql-java-kickstart</a></p><p>You only need one dependency to start writing graphql APIs. .</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/681/1*gJYfySieM8oalWNLSiMBww.png" /><figcaption>pom dependency for graphql-java-kickstart</figcaption></figure><p><strong>dgs-framework</strong></p><p>Released/Open-sourced on November’20, developed Netflix, this library is the latest addition to the graphql community with Spring Boot. And from the looks of it, this library has it all.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/522/1*VqpoOu6i0Hgtq-GqPR8TYQ.png" /></figure><p>Current version is 4.5.0 and last released on July’21.</p><p>Documentation: <a href="https://netflix.github.io/dgs/">https://netflix.github.io/dgs/</a></p><p>Code: <a href="https://github.com/Netflix/dgs-framework">https://github.com/Netflix/dgs-framework</a></p><p>You only need one dependency to start coding GraphQL APIs with this library.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/681/1*uAo6NEaP9fwpb89srlIZkw.png" /><figcaption>pom dependency for dgs-framework</figcaption></figure><h3>Comparative study</h3><h4>Application Architecture</h4><p>How does your code base look like if you want to implement GraphQL with any of these libraries.</p><p>I will take an example of a simple microservice, implemented with Controller-Service-Repository architecture with an H2 database in-memory. But you can also choose to replace the repository with external service/endpoint calls without changing the way you would expose GraphQL.</p><p><strong>Sample baseline application</strong></p><p>For the sample baseline application to compare with I will refer to a <a href="https://medium.com/springboot-chronicles/api-first-approach-with-openapi-contracts-maven-spring-boot-6aa9b9251341">previous blog</a> I wrote.</p><p>Code: <a href="https://github.com/sohamda/serivce-repository-swagger">https://github.com/sohamda/serivce-repository-swagger</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MnWZGp6w_zAZ_lBoTHf8rw.png" /><figcaption>baseline application structure</figcaption></figure><p><strong>Application architecture for “graphql-java”</strong></p><p>You need Dataloader &amp; Datafetcher to map Service/Repository implementations, Dataregistry to map N+1 queries to DataLoaders, GraphQLSchema for parsing the graphql schema and Runtimewiring to map queries and mutations to Datafetchers.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JncfgyiPdNmzygGNQudVTg.png" /><figcaption>graphql-java application structure</figcaption></figure><p><strong>Application architecture for “graphql-java-kickstart”</strong></p><p>You need Resolvers to map graphql schema definitions to Service/Repository methods, DataRegistry to map N+1 queries and GraphQLServletContextBuilder to define Dataregistry.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7nsIt27wihFh09ziOaeV3w.png" /><figcaption>graphql-java-kickstart application structure</figcaption></figure><p><strong>Application architecture for “dgs-framework”</strong></p><p>This uses a annotation based model, so @DgsData for mapping graphql schema definitions and @DgsDataLoader for N+1 queries.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cvM3nw0AR-4tVG0HPl_w7w.png" /><figcaption>dgs-framework application structure</figcaption></figure><h3>Code level comparison among the 3 libraries</h3><h4>Code structure with “graphql-java”</h4><p>Following are the implementation details of GraphQL API with “graphql-java” libary.</p><p>The code is in Github: <a href="https://github.com/sohamda/graphql-java">https://github.com/sohamda/graphql-java</a></p><ol><li>Create @Component classes to define the DataFetchers. These have methods with return type DataFetcher which maps to the Service or Repository methods.</li><li>Define a @Component class to define a GraphQL bean.</li><li>In a @PostConstruct of this class, parse/build the graphql schema.</li><li>Also define the mapping(RuntimeWiring) of the graphql schema definitions (query, mutation, field-level mapping) to associated DataFetchers, defined in Step #1.</li><li>For N+1 queries, define a DataLoader(method with return type BatchLoader/MapLoader) in a @Component class. Then define a DataLoaderRegistry bean which maps the DataLoader to a “key”. This key will be the trigger for the runtime to invoke the DataLoader.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NbOKJOZ5JhbI6irCK1ChrQ.png" /><figcaption>example: graphql-java</figcaption></figure><h4>Code structure with “graphql-java-kickstart”</h4><p>Following are the implementation details of GraphQL API with “graphql-java-kickstart” libary.</p><p>The code is in Github: <a href="https://github.com/sohamda/graphql-java-kickstart">https://github.com/sohamda/graphql-java-kickstart</a></p><ol><li>Define @Component class for mapping the graphql schema Query operations which implements GraphQLQueryResolver. The query definitions should match the method names. That’s how the schema to code mapping happens at runtime. Within these methods you call the Service or Repository classes.</li><li>Define @Component class for mapping the graphql schema Mutation operations which implements GraphQLMutationResolver. The query definitions should match the method names. That’s how the schema to code mapping happens at runtime. Within these methods you call the Service or Repository classes.</li><li>Define @Component class for the field-level mappings, this should implement GraphQLResolver&lt;T&gt;. Within these methods you call the Service or Repository classes.</li><li>For N+1 queries, define a @Component class which defines the DataLoader and defines the DataLoaderRegistry. Then define another @Component class which implements GraphQLServletContextBuilder to actually register the DataLoaderRegistry.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jmeIvHnPY_O9PTsUTcCHsw.png" /><figcaption>example: graphql-java-kickstart</figcaption></figure><h4>Code structure with “dgs-framework”</h4><p>Following are the implementation details of GraphQL API with “dgs-framework” libary.</p><p>The code is in Github: <a href="https://github.com/sohamda/graphql-dgs-netflix">https://github.com/sohamda/graphql-dgs-netflix</a></p><ol><li>Define a class with @DgsComponent annotation and declare methods with @DgsData annotations to map graphql schema query, mutations and field-level mappings. Within these methods you call the Service or Repository classes.</li><li>For N+1 queries, define a class with @DgsDataLoader which implements BatchLoader or MapLoader and implement the required method to return a CompletableFuture.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2eMBio3q8fmIlTLUTpBwrw.png" /><figcaption>example: dgs-framework</figcaption></figure><h4>Error handling with “graphql-java”, “graphql-java-kickstart” and “dgs-framework”</h4><p>It is important to mention, a GraphQL API always returns a 200, even in the case of server side exceptions and errors, what you get back is an error object with details of the error in it.</p><p>All these 3 libraries have their own way of handling errors.</p><ol><li>graphql-java: You need to implement GraphQLError interface and override the methods.</li><li>graphql-java-kickstart: This library provides two ways to handle errors, the spring boot way of defining exception handler beans or a component class which implements GraphQLErrorHandler and there you can manage the errors the way you want to.</li><li>dgs-framework: You need to define a component which implements DataFetcherExceptionHandler and then manage the errors inside the overridden method.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KL9YA3jHMABdZ90zl5AjlA.png" /><figcaption>example: error handling in 3 different libraries</figcaption></figure><h4>Java client for “graphql-java”, “graphql-java-kickstart” and “dgs-framework”</h4><p>While it is quite interesting to implement the server side of GraphQL APIs, but it is also quite important to explore on how would such APIs will be consumed.</p><ol><li>graphql-java: This library has no defined way to create Java clients. The only way to do it is define some text templates(mustach) and generate the query and mutation request at runtime. Then just use RestTemplate/Feign/Webclient (or your choice of client library) to do a post request to the endpoint.</li><li>graphql-java-kickstart: This library provides a Webclient library to call a GraphQL endpoint, but although you still need to use text templates(mustach) to generate the query and mutation request at runtime.</li><li>dgs-framework: This library provides GraphQLClient which can be used with text templates as the previous two. But they also provides a Gradle plugin to generate the model classes, which you can use to generate the request in a type-safe way. This is a huge improvement from the text templates, since the schema file can be used as single source of truth for server side as well as client side.</li></ol><p>You can find the sample client code in here: <a href="https://github.com/sohamda/graphql-restclient">https://github.com/sohamda/graphql-restclient</a></p><h4>Image-size &amp; Runtime memory consumption for “graphql-java”, “graphql-java-kickstart” and “dgs-framework”</h4><p>If containerized and ran on a container platform the applications doesn’t show that much of a difference in image sizes or memory consumption on the tests I did on my sample applications.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hD2zulLi2t1-m9eptWLxEg.png" /><figcaption>example: image sizes &amp; runtime memory</figcaption></figure><h3>Final Words</h3><p>Been working with all 3 of these libraries for sometime now, although dgs-framework is very new but the other libs are very matured and has evolved with the time. All these libraries have a strong community presence, so it is easy to find help around specific questions/issues. So, it doesn’t really matter which one you choose to implement your GraphQL endpoints. But, as an honest opinion from the author self, “dgs-framework” is a winner for me here.</p><p>“dgs-framework” is being used internally at Netflix for couple of years before they open-sourced it. Implementation easiness, annotation driven structure, code-generation, error handling flexibility are the strongest points of this library over others. So my recommendation : dgs-framework</p><p>All code used for this blog can be found <a href="https://github.com/sohamda?tab=repositories&amp;q=graph&amp;type=&amp;language=&amp;sort=">here</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b0e8d544f2fc" width="1" height="1" alt=""><hr><p><a href="https://medium.com/springboot-chronicles/graphql-in-springboot-a-comparative-study-among-the-libraries-and-their-implementation-know-how-b0e8d544f2fc">GraphQL in Springboot : A comparative study among the libraries and their implementation know-how</a> was originally published in <a href="https://medium.com/springboot-chronicles">springboot-chronicles</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How we managed to bring down memory footprint of our Spring Boot micro services — A case study]]></title>
            <link>https://medium.com/springboot-chronicles/how-we-managed-to-bring-down-memory-footprint-of-our-spring-boot-micro-services-a-case-study-b41dd94e6c27?source=rss----5d14c3ef5095---4</link>
            <guid isPermaLink="false">https://medium.com/p/b41dd94e6c27</guid>
            <category><![CDATA[spring-boot-memory-usage]]></category>
            <category><![CDATA[spring-boot]]></category>
            <category><![CDATA[spring-boot-jvm]]></category>
            <category><![CDATA[microservices]]></category>
            <category><![CDATA[openj9]]></category>
            <dc:creator><![CDATA[Soham Dasgupta]]></dc:creator>
            <pubDate>Tue, 27 Apr 2021 09:33:00 GMT</pubDate>
            <atom:updated>2021-04-27T09:32:57.314Z</atom:updated>
            <content:encoded><![CDATA[<h3>How we managed to bring down memory footprint of our Spring Boot microservices — A case study</h3><p>Since I restarted my Java journey last year, I have been busy working with Spring Boot day-in and day-out. My client right now has a few one-pager applications and 20–30 supporting microservices and almost 99% of them are Spring Boot. These microservices not only interact with each other but also Keydb, MySQL database and few external services.</p><p>Since last year my client moved to a containerized application development — delivery-deployment architecture, which definitely streamlined CI/CD but brought a few side effects with it. And one the biggest one is memory footprint/consumption by these containerized applications.</p><p>To give an example, a simple GET which is querying a table from a MySQL database on properly indexed columns requires startup and runtime memory close to 600 MB. So, if we scale this service up by 3 instances/pods already a 2GB memory footprint for a simple Spring Boot application. And for 20–30 services, each having 3 instances (or pods) running, is going to cost our client close to 60–100GB to run their platform.</p><p>This was a huge problem for us, since we needed to think carefully which services, we want to scale which we cannot simply because we had only 40GB memory available. This made us started investigating on what is going wrong and where we can make things better. We even questioned about the choice of Spring Boot and maybe rewrite a few simple services in Express/Node JS.</p><h3>Diving-Deep</h3><p>We went on wild-goose-chase almost to find the root cause of our memory issues, read articles from every possible sources, because we couldn’t believe that no-one every faced this before. What we were looking for was an article like this, a white paper about their struggle and success with memory footprint issue with Spring Boot.</p><p>We found a few interesting articles and discussions online, which helped us in right direction:</p><p>1. <a href="https://spring.io/blog/2019/03/11/memory-footprint-of-the-jvm">Spring Blog over memory usage</a></p><p>2. <a href="https://dzone.com/articles/memory-wasted-by-spring-boot-application">DZone blog over spring memory usage and how to track details</a></p><p>3. Stackoverflow discussion: <a href="https://stackoverflow.com/questions/44491257/how-to-reduce-spring-boot-memory-usage">about JVM params</a></p><p>4. Stackoverflow discussion: <a href="https://stackoverflow.com/questions/57271442/how-can-i-decrease-spring-boot-application-memory-usage-in-docker">runtime docker container settings</a></p><p>5. Stackoverflow discussion: <a href="https://stackoverflow.com/questions/32942259/how-to-run-spring-boot-fat-jar-with-minimal-memory">running jar with minimal memory settings</a></p><p>6. <a href="https://medium.com/@jean_sossmeier/spring-boot-jvm-1eea422be930">Jean Luc Sossmeier’s blog about OpenJ9</a></p><p>The more we dived deeper, it became quite clear to us, that Spring Boot is not what makes the runtime memory go up, ofcourse there are some framework defaults which adds to this but not so much of memory consumption.</p><p>So, we started looking at the runtime container instance and the JVM parameters, because we were quite sure that’s where we have some quick wins.</p><h3>The base-line</h3><p>We setup 3 microservices which interacts with each other and also with Spring config server, KeyDB and MySQL. And tested this with JMeter with varied load and setup.</p><p>We invoked 1 microservice for our test, which interacts with 2 other microservices and they all retrieve their config from a spring cloud config and also interacts with KeyDb and MySQL.</p><p>The sequence of actions looks like below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pgMNyPk61yjCZTqvrvMlsg.png" /><figcaption>Test setup interaction diagram</figcaption></figure><p>And the setup is as below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/904/1*RTJSLsZSz1iOSo27JweQMQ.png" /></figure><h3>Spring Boot &amp; JVM config</h3><p>We researched about this quite intensively and found that there is a max thread setup and max connection parameter which gives startup and runtime memory quite a boost.</p><p>server.tomcat.max-connections=20<br>server.tomcat.threads.max=5</p><p>Although please read and adjust this according to your production requirements, Tomcat documentation can be found <a href="https://tomcat.apache.org/tomcat-8.5-doc/config/http.html">here</a>.</p><p>For JVM parameters apart from a fixed Xmx, we used:</p><p>1. -XX:MaxRAM=150m (Or -XX:MaxRAMPercentage=70)</p><p>2. -XX:+UseSerialGC</p><p>3. -Xshareclasses</p><p>4. -Xquickstart</p><h3>Container base-image</h3><p>The biggest memory footprint reduction we saw is due to this, i.e., moving to a different base image while building our images.</p><p>We ran our tests on containers build with base image <a href="https://hub.docker.com/_/openjdk">OpenJDK</a> for Java 8 and 11 and <a href="https://hub.docker.com/_/adoptopenjdk">OpenJ9</a>.</p><p>The runtime and startup memory footprint were reduced for some cases almost 70% that too with an increase in Transaction per second value.</p><h3>The Test and Results</h3><p>We ran a JMeter load test with the following settings:</p><p>· Load: 20 concurrent threads with 500 requests per thread with no delay, which is 10000 transactions.</p><p>What we measured:</p><p>· Throughput (transactions per second)</p><p>· Image size</p><p>· Memory usage before, during and after the test.</p><p>Image Size with Base image as</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vpzIzucvj3BnbkVIrnM6ug.png" /></figure><p>First set of tests were ran with out an Xmx value on the JVM and we calculated Transaction per second(tps) on “Microservice A”.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*j1CQi8dGout_yUi-K1IOww.png" /><figcaption>test results with only base image variations</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RAS8EiZL8o8xjn9FiFX47w.png" /><figcaption>memory usage average</figcaption></figure><p>Then we repeated our test with Xmx=512 MB. Although we needed to set Xmx value only when we used OpenJDK 8 as our base image, for all other tests it was via docker-compose.yaml .</p><p>OpenJDK 8 crashed when it reached memory limit specified in container resources, we had to specifically set this as JVM parameter.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CxFSIREh8ZSqjdmHsINj_w.png" /><figcaption>test results with only base image variation</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6V3XLF8VDhGG8JH39BL6QA.png" /><figcaption>memory usage average</figcaption></figure><h3>Recommendations</h3><p>OpenJ9 as your base image with some application properties and JVM parameters gave us the best outcomes. So, we recommend OpenJ9. Our tests also showed OpenJDK 8 as base image has worst memory footprint and also not very container aware.</p><h3>Contributors</h3><p>This article could not have been written without the help from <a href="https://www.linkedin.com/in/ianvanstaden/">Ian van Staden</a>. My sincere thanks Ian :)</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b41dd94e6c27" width="1" height="1" alt=""><hr><p><a href="https://medium.com/springboot-chronicles/how-we-managed-to-bring-down-memory-footprint-of-our-spring-boot-micro-services-a-case-study-b41dd94e6c27">How we managed to bring down memory footprint of our Spring Boot micro services — A case study</a> was originally published in <a href="https://medium.com/springboot-chronicles">springboot-chronicles</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[API first approach with OpenAPI contracts, Maven & Spring Boot]]></title>
            <link>https://medium.com/springboot-chronicles/api-first-approach-with-openapi-contracts-maven-spring-boot-6aa9b9251341?source=rss----5d14c3ef5095---4</link>
            <guid isPermaLink="false">https://medium.com/p/6aa9b9251341</guid>
            <category><![CDATA[maven-plugin]]></category>
            <category><![CDATA[spring-boot]]></category>
            <category><![CDATA[aos]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[open-api]]></category>
            <dc:creator><![CDATA[Soham Dasgupta]]></dc:creator>
            <pubDate>Mon, 15 Mar 2021 17:31:26 GMT</pubDate>
            <atom:updated>2021-03-15T17:31:24.172Z</atom:updated>
            <content:encoded><![CDATA[<p>API first approach has a ton of advantage’s, it helps developers and functional analysts to visualize the APIs before developers start implementing it. It also helps the UI developers and the testers to start working on their tasks parallel while developers are busy implementing.</p><p>In this blog I will explain how to create such API contracts with Swagger 3.0 on OpenAPI specifications (OAS) and using Maven, how can we easily generate Spring Boot code for such contracts.</p><h3>Swagger/OpenAPI contract</h3><blockquote><em>The OpenAPI Specification (OAS) defines a standard, language-agnostic interface to RESTful APIs which allows both humans and computers to discover and understand the capabilities of the service without access to source code, documentation, or through network traffic inspection. When properly defined, a consumer can understand and interact with the remote service with a minimal amount of implementation logic.</em></blockquote><blockquote><em>An OpenAPI definition can then be used by documentation generation tools to display the API, code generation tools to generate servers and clients in various programming languages, testing tools, and many other use cases.</em></blockquote><blockquote>- <em>Source : </em><a href="https://swagger.io/specification/"><em>https://swagger.io/specification/</em></a></blockquote><p>OpenAPI specs has a few major sections while defining the APIs:</p><p>- Info</p><p>- Tags</p><p>- Paths</p><p>- Components</p><p><em>Info</em>: Holds API title, description, version, contact and license information.</p><p><em>Tags</em>: Holds different tags for the API definitions, a useful way to segregate APIs, this is quite useful if you are using Swagger editor to navigate the APIs. You are can also use tags to document your APIs better.</p><p><em>Paths</em>: As the name suggests, it holds all your API paths. It defines, the REST operation, description, request, response structures and HTTP response codes.</p><p><em>Components</em>: This is to define the objects (models) you use in your API definitions also the reusable HTTP response codes.</p><p>While generating code using Maven plugin, paths and components are being leveraged to generate code.</p><p>The example is based on my previous blog on <a href="https://medium.com/springboot-chronicles/manage-database-changes-with-liquibase-in-spring-boot-256dbe156717">Liquibase+Spring boot</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/922/1*x6Pcq8YNADanL53EaZvipA.png" /><figcaption>datamodel — provider, service, citizen</figcaption></figure><p>Example API spec : <a href="https://github.com/sohamda/serivce-repository-swagger/blob/master/src/main/resources/apispec/openapi3.yaml">API Spec for Providers/Services</a> (I have excluded Citizen APIs for the time being)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/904/1*AEIhCD_qF-BJTR9H8gGKRw.png" /><figcaption>Swagger Contract</figcaption></figure><p>As you can see above, I have defined 7 endpoints, with some standard info and a couple of tags.</p><p>Lets dive into one of the paths:</p><p>This is a get all services endpoint, which returns an array of “Service” objects (this is defined in components, that’s why a $ref). It also defines that it is being tagged as Service API and other HTTP error codes with a return message.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/574/1*bkwyRZzUoDOjom2UC2C4cA.png" /><figcaption>Services endpoint</figcaption></figure><p>Above, the “operationId” will be later used to generate the controller method name.</p><p>How does a component looks like:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/560/1*nRtNzmSUhRrWyLu6M_qU2w.png" /><figcaption>Service Model</figcaption></figure><p>Here you define the basic object structure with some example values and also if this object also refers to another object within the components (such as Provider).</p><p>More info, on how to define such contracts using OAS can be found <a href="https://github.com/OAI/OpenAPI-Specification/blob/master/versions/3.0.2.md#versions">here</a>.</p><h3>Code generation</h3><p>Code generation can be for server (the API implementation itself) or client (connecting the API). Although, for client you can still choose use Feign clients for more diverse and sophisticated implementation depending on your requirements.</p><p>I will concentrate on the server side of it, since that’s reduces a lot of boilerplate code for you.</p><p>The easiest way to do this, is to use <a href="https://editor.swagger.io/">https://editor.swagger.io/</a> and do this from the browser, if you choose to. But this won’t help you to make generation and maintenance easier.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/904/1*rkcvGC631sFWc3Qi9kiUGQ.png" /><figcaption>Swagger Editor Code Gen</figcaption></figure><h3>Maven plugin</h3><p>OpenAPI provides an useful maven plugin which you can use to generate the code from these types of contracts.</p><p>Link to repo is <a href="https://github.com/OpenAPITools/openapi-generator/tree/master/modules/openapi-generator-maven-plugin">here</a>.</p><p>The documentation talks about all the properties you can configure to generate server or a client. I will show you my example on the server part.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/852/1*dtocEAbY-zkyBwzwda0zSg.png" /><figcaption>maven open-api plugin — server</figcaption></figure><p>A few major properties are, where to find the yaml file containing the specs, package names for your generated classes.</p><p>With the spec, I shared earlier, if we use the above plugin, the generated classes looks like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/480/1*B5jwfUmQNLj6kMs8wGxxHQ.png" /><figcaption>Generated Classes — OpenAPI</figcaption></figure><p>FYI: I faced a few compilation errors, due to unused imports in the generated classes, which you can avoid by using a different template.</p><p>More info on:</p><p>- <a href="https://github.com/OpenAPITools/openapi-generator/issues/8776">https://github.com/OpenAPITools/openapi-generator/issues/8776</a></p><p>- <a href="https://github.com/OpenAPITools/openapi-generator/issues/2901">https://github.com/OpenAPITools/openapi-generator/issues/2901</a></p><p>I had to add some extra dependencies to resolve this, you can also do that temporarily to avoid compilation issues.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/586/1*8m6GAfZqOS5rr96gaQz7Ig.png" /><figcaption>added dependencies</figcaption></figure><h3>Closer look at the generated classes</h3><h3>API-Controller-Delegate</h3><p>OpenAPI plugin generates 2 interfaces and 1 class. One interface for API which gets implemented by Controller, they both combined defines the endpoints.</p><p>There will be as many number of API-Controller combination as the number of “paths” you have defined in the yaml.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/810/1*os-8hm9rkJIM1xMjTuMwPA.png" /><figcaption>Class Diagram from Intellij</figcaption></figure><p>Another interface, xxxDelegate which should be implemented by a @Service implementation of Spring Boot.</p><p>The delegate interface, comes from the plugin config properties, delegatePattern = true. You can choose to disable this, but I find it quite useful from the perspective of “separation-of-concerns” concept.</p><h3>Model</h3><p>The plugin also generates all the model objects defined in the components section of the API spec.</p><p>This is a simple POJO with all defined properties from the spec with annotations defining non-nulls, required etc. attributes.</p><h3>Complete the implementation with Service &amp; Repository</h3><p>Now that we have the basic code generated for the endpoints, we just need to implement the repository and service classes (and possibly the entities). In this example, I have also created the entities, since I like to keep the response-request objects separated from the DB structure.</p><p>BTW, the convertion between entity-to-response object has been done using <a href="https://mapstruct.org/">Mapstruct</a>.</p><p>The complete implementation is in <a href="https://github.com/sohamda/serivce-repository-swagger">Github</a>.</p><h3>Running the application</h3><p>If you just run the SerivceRepositoryApplication class, all the APIs will be available and you can invoke them using your favorite client.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/734/1*BjK66eESDCbTnCFJ2waMuA.png" /><figcaption>Services GET endpoint</figcaption></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6aa9b9251341" width="1" height="1" alt=""><hr><p><a href="https://medium.com/springboot-chronicles/api-first-approach-with-openapi-contracts-maven-spring-boot-6aa9b9251341">API first approach with OpenAPI contracts, Maven &amp; Spring Boot</a> was originally published in <a href="https://medium.com/springboot-chronicles">springboot-chronicles</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Manage database changes with Liquibase in Spring Boot]]></title>
            <link>https://medium.com/springboot-chronicles/manage-database-changes-with-liquibase-in-spring-boot-256dbe156717?source=rss----5d14c3ef5095---4</link>
            <guid isPermaLink="false">https://medium.com/p/256dbe156717</guid>
            <category><![CDATA[liquibase]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[mysql]]></category>
            <category><![CDATA[spring-boot]]></category>
            <category><![CDATA[h2-database]]></category>
            <dc:creator><![CDATA[Soham Dasgupta]]></dc:creator>
            <pubDate>Sun, 14 Mar 2021 19:33:06 GMT</pubDate>
            <atom:updated>2021-03-14T19:42:08.649Z</atom:updated>
            <content:encoded><![CDATA[<p>I have restarted my Java journey almost an year ago after a few years of complete Javascript. And since then, I have been solely working on creating micro-components and services using Springboot. But the journey doesn’t only include Springboot and Java but almost everything surrounding the Cloud Native eco-system. For today’s blog it is Liquibase.</p><h4>What is Liquibase:</h4><p>Liquibase is a tool to track, version, and deploy database changes. It uses <em>changesets</em> to represent a single change to your database. Each changeset has an “id” and “author” attribute which, along with the directory and file name of the changelog file, uniquely identify it. There are four different ways to define your changes: SQL, XML, YAML, and JSON formats. So you can version control your DB changes easily and depending on your/team’s preferred language. Liquibase uses a <em>changelog</em> to explicitly list database changes in order. Not only that, Liquibase tracks which changeSets have or have not been deployed in a tracking table called a DATABASECHANGELOG.</p><p>More info : <a href="https://www.liquibase.org/get-started">https://www.liquibase.org/get-started</a></p><h4>How does changelog look like</h4><p>In this example I use XML format, but it is pretty much similar for YAML and JSON. (I personally feel, if you are moving to Liquibase you should stop doing SQL for your DB changes.)</p><p>Below is an example of create table, quite self-explanatory. A changelog can contain 1 or more changeSet defining the database operation you want to perform.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/904/1*Tt21JR3-t38M-aZdZ7hWfw.png" /><figcaption>Example — Changelog file</figcaption></figure><p>There are several things you can do in changelog/changeset, check out the documentation: <a href="https://docs.liquibase.com/concepts/home.html">https://docs.liquibase.com/concepts/home.html</a></p><h4>Spring Boot and Liquibase</h4><p>Spring Boot provides out-of-the-box support for Liquibase, the only dependency you would need along with some properties (in application properties) is :</p><pre>&lt;dependency&gt;<br>   &lt;groupId&gt;org.liquibase&lt;/groupId&gt;<br>   &lt;artifactId&gt;liquibase-core&lt;/artifactId&gt;<br>&lt;/dependency&gt;</pre><h3>To create a Spring Boot application with Liquibase as database management</h3><h4>Step 1: Initialize your project</h4><p>Create a simple project from <a href="http://start.spring.io/">start.spring.io</a> (I have used JPA, if can alternatively use JDBC as well)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/904/1*XooQ5XWAf2o5gTJM_1sxMQ.png" /><figcaption>spring initializer</figcaption></figure><p>Once you download and import in your IDE, it would look like this :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/888/1*DCvJ9m3mz_t__z7hNNumhQ.png" /><figcaption>project-structure</figcaption></figure><p>Your pom.xml would look like :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/904/1*0kQdEjnPiW1DCS91h48weg.png" /><figcaption>pom file — part 1</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/904/1*HyPckKKUmpJa2yRu_wKQyQ.png" /><figcaption>pom file — part 2</figcaption></figure><h4>Step 2: Add ChangeLogs &amp; changeSets</h4><p>In this example I have 3 tables and one intersection table.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/922/1*x6Pcq8YNADanL53EaZvipA.png" /><figcaption>datamodel</figcaption></figure><p>I have separated the create table and insert data files for better understanding and one master-changelog to define the sequence of execution.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/904/1*s8xoANiv9sO9ZeBV351iWg.png" /><figcaption>changelogs</figcaption></figure><h4>Step 3: Define spring properties</h4><p>The last step of configuration is defining the spring props for liquibase, h2 database.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/904/1*oMmP9OvBodf-8bbg12m7Xg.png" /><figcaption>application.properties</figcaption></figure><p>I have used 2 props for liquibase, there are several others, you can check it <a href="https://github.com/spring-projects/spring-boot/blob/v2.4.2/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/liquibase/LiquibaseProperties.java">here</a>. Above, I had to specify the location of the changelog because it is a xml, for yaml you don’t need to.</p><p>Alternatively, if you are using a MySQL database, you app properties will have the below:</p><pre><em># MySQL<br></em>spring.datasource.url=jdbc:mysql://0.0.0.0:3306/liquibase_demo<br>spring.datasource.username=liquibase_demo<br>spring.datasource.password=liquibase_demo<br>spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver</pre><p>And you would need a different dependency than h2 :</p><pre>&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;</pre><h4>Running the application</h4><p>Once you generate the jar and run it, you would see logs of tables getting created and data getting inserted.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/904/1*veNmGJWAJ1sItadJkWWNhA.png" /><figcaption>Application startup log</figcaption></figure><p>And once started, you can check the tables in the h2 console on your browser:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/904/1*qCtRavhYDpfMq7njihAsmQ.png" /><figcaption>H2 console</figcaption></figure><p><strong><em>TL;DR :</em></strong></p><p>Github Repos :</p><p>- <a href="https://github.com/sohamda/liquibase-h2">with H2 database</a></p><p>- <a href="https://github.com/sohamda/liquibase-h2/tree/with-mysql-dependency">with MySQL database</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=256dbe156717" width="1" height="1" alt=""><hr><p><a href="https://medium.com/springboot-chronicles/manage-database-changes-with-liquibase-in-spring-boot-256dbe156717">Manage database changes with Liquibase in Spring Boot</a> was originally published in <a href="https://medium.com/springboot-chronicles">springboot-chronicles</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>