<?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 Devindi Jayathilaka on Medium]]></title>
        <description><![CDATA[Stories by Devindi Jayathilaka on Medium]]></description>
        <link>https://medium.com/@devindijayathilaka?source=rss-82c5800e623------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*Tudljoa3P9zF6csnpQflXg.png</url>
            <title>Stories by Devindi Jayathilaka on Medium</title>
            <link>https://medium.com/@devindijayathilaka?source=rss-82c5800e623------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 04 Dec 2026 18:32:42 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@devindijayathilaka/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[Exploring Microservices Architecture]]></title>
            <link>https://devindijayathilaka.medium.com/exploring-microservices-architecture-3364577bc305?source=rss-82c5800e623------2</link>
            <guid isPermaLink="false">https://medium.com/p/3364577bc305</guid>
            <category><![CDATA[api-gateway]]></category>
            <category><![CDATA[service-registry]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[spring-boot]]></category>
            <category><![CDATA[microservice-architecture]]></category>
            <dc:creator><![CDATA[Devindi Jayathilaka]]></dc:creator>
            <pubDate>Sat, 12 Jul 2025 11:48:15 GMT</pubDate>
            <atom:updated>2025-07-12T11:48:15.091Z</atom:updated>
            <content:encoded><![CDATA[<p>Building Microservices with Spring Boot: A Practical Guide</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Ux-LQ61SI5UDJouo" /><figcaption>Photo by <a href="https://unsplash.com/@a_chosensoul?utm_source=medium&amp;utm_medium=referral">A Chosen Soul</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Hi everyone👋</p><p>I hope this article remains timely and relevant, despite the rapid evolution of technology.</p><p>As a backend developer, I want to move beyond theory and experience of microservices architecture in action. So I decided to build a small yet practical project to sharpen my understanding of <strong>Spring Boot</strong>, <strong>Spring Cloud</strong>, and <strong>microservices fundamentals</strong>.</p><p>If you’re new to Microservices architecture, first read the article below, which helps you understand how microservices address the limitations of <strong>monolithic architecture</strong>.</p><p><a href="https://javarevisited.substack.com/p/difference-between-microservices?source=post_page-----4266f440086f---------------------------------------">Difference between Microservices and Monolithic Architecture</a></p><p>Let&#39;s start building our microservice project.</p><p><strong>Tech Stack &amp; Tools⚙️</strong></p><ul><li><strong>Java 17</strong></li><li><strong>Spring Boot</strong> (for building microservices)</li><li><strong>Spring Cloud Eureka</strong> (for service discovery)</li><li><strong>Spring Cloud Gateway</strong> (for API gateway routing)</li><li><strong>Maven</strong> (for build management)</li><li><strong>MySQL</strong> (databases for each service)</li><li><strong>Postman</strong> (for testing APIs)</li></ul><p>If you are new to Spring Boot, follow the article below and gain experience in building CRUD operations</p><p><a href="https://medium.com/linkit-intecs/how-to-connect-spring-application-with-mysql-database-55821314ba5">How to connect spring application with MySql Database</a></p><p>This is about a simple E-commerce project where users can place orders for their desired products. Here I am focusing on two microservices only, the order service and the product service. To maintain simplicity, this example does not include user management.</p><p>Microservices Breakdown</p><ol><li>Service Registry</li><li>Order service</li><li>Product service</li><li>API Gateway</li></ol><p><strong>Why Service Registry?</strong></p><p>Before developing individual services, you need to set up the <strong>Eureka Server</strong>, which acts as the <strong>Service Registry</strong>. You may be curious about the service registry</p><p>In production, services are often running on <strong>multiple instances</strong>. These instances may start, stop or restart at any time, sometimes with <strong>different IPs and ports</strong>. So if you hard-code service URLs, your system breaks when an instance changes. In a microservices system, this registry enables services to discover each other dynamically without hard-coded IPs or URLs.</p><p><strong>Setting Up the Service Registry: Eureka Server</strong></p><ul><li>Create a new Spring Boot project and add the spring-cloud-starter-netflix-eureka-server dependency.</li><li>Enable the Eureka Server by adding @EnableEurekaServer to the main application class.</li></ul><pre>package com.ecom.eureka_server;<br><br>import org.springframework.boot.SpringApplication;<br>import org.springframework.boot.autoconfigure.SpringBootApplication;<br>import org.springframework.cloud.netflix.eureka.server.EnableEurekaServer;<br><br>@SpringBootApplication<br>@EnableEurekaServer<br>public class EurekaServerApplication {<br><br> public static void main(String[] args) {<br>  SpringApplication.run(EurekaServerApplication.class, args);<br> }<br>}</pre><ul><li>Configure the application.properties with basic port and Eureka-related settings.Eureka port <strong>8761</strong>, which is the common default.</li></ul><pre>spring.application.name=service-registry<br><br># Eureka Server port for communication with client applications<br>server.port=8761<br><br># Disables the Eureka client&#39;s capability to fetch the registry <br># of other services from the Eureka server, as it is not acting as a Eureka client.<br>eureka.client.fetch-registry=false<br><br># Disables the Eureka client&#39;s registration with the Eureka server. <br># Since this application is the Eureka server itself, <br># it does not need to register with any other Eureka server.<br>eureka.client.register-with-eureka=false</pre><p>Now let&#39;s run our Eureka server application. Eureka dashboard can be visible on <a href="http://localhost:8761/">http://localhost:8761/</a> as below</p><figure><img alt="Eureka Dashboard" src="https://cdn-images-1.medium.com/max/1024/1*2ZXXNvHdGMQ0NmWuyM4dGw.png" /><figcaption>Eureka Dashboard</figcaption></figure><p>At this stage, since we haven’t developed or run any microservices yet, the Eureka dashboard displays a “No instances available” message. Once our services are up and running, they will automatically register with Eureka and appear under the Instances section. So, let’s build our first microservice and register it with the Eureka server</p><h4>Order Service</h4><p>For the moment, I am focusing only on the <strong>order creation</strong> and <strong>retrieving order details</strong> functionalities to keep the implementation simple and easy to follow. Additional features can be added later as the project evolves.</p><p>Create a Spring Boot application with the following dependencies</p><pre>&lt;dependencies&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;org.springframework.cloud&lt;/groupId&gt;<br>   &lt;artifactId&gt;spring-cloud-starter-netflix-eureka-client&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-data-jpa&lt;/artifactId&gt;<br>  &lt;/dependency&gt;<br>  &lt;dependency&gt;<br>   &lt;groupId&gt;com.mysql&lt;/groupId&gt;<br>   &lt;artifactId&gt;mysql-connector-j&lt;/artifactId&gt;<br>   &lt;scope&gt;runtime&lt;/scope&gt;<br>  &lt;/dependency&gt;<br>&lt;/dependencies&gt;</pre><p>In microservices architecture, each service has its own respective database. So you need to create order service-related database now. I chose MySQL to create database for this project, but you’re free to use any database of your choice based on your preference or project requirements.</p><p>Then register the Order service with Eureka. In your application class, use <a href="https://www.java67.com/2018/12/top-5-spring-cloud-annotations-for-java.html">@EnableDiscoveryClient</a> annotation to enable service discovery functionality in the Spring Boot application. It signifies that this microservice will register itself with a service registry.</p><pre>package com.ecom.order_service;<br><br>import org.springframework.boot.SpringApplication;<br>import org.springframework.boot.autoconfigure.SpringBootApplication;<br>import org.springframework.cloud.client.discovery.EnableDiscoveryClient;<br><br>@SpringBootApplication<br>@EnableDiscoveryClient<br>public class OrderServiceApplication {<br><br> public static void main(String[] args) {<br>  SpringApplication.run(OrderServiceApplication.class, args);<br> }<br>}</pre><p>Configure the application.properties</p><pre>spring.application.name=order-service<br>server.port=8082<br><br>#database configurations<br>spring.datasource.url=jdbc:mysql://localhost:3306/orderdb<br>spring.datasource.username=root<br>spring.datasource.password=password<br><br>spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver<br><br>spring.jpa.hibernate.ddl-auto=update<br>spring.jpa.show-sql=true<br>spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.MySQL8Dialect<br><br>eureka.client.register-with-eureka=true<br>eureka.client.fetch-registry=true<br>eureka.client.service-url.defaultZone=http://localhost:8761/eureka/<br>eureka.instance.prefer-ip-address=true<br>eureka.instance.ip-address=127.0.0.1</pre><p>In each microservice’s configuration, I have added Eureka client properties to enable service registration and discovery. These settings tell the service to register itself with the Eureka Server running on localhost:8761 and prefer using its IP address when communicating with other services.</p><p>These are the configurations that need to be registered in the Eureka server. Next, let’s build the business logic of the project.</p><p><em>Create Order Entity class</em></p><pre>@Entity<br>@Table (name = &quot;orders&quot;)<br>public class Order {<br><br>    @Id<br>    @GeneratedValue(strategy = GenerationType.IDENTITY)<br>    private Long id;<br><br>    private Long userId;<br><br>    private Long productId;<br><br>    private Integer quantity;<br><br>    private Double totalPrice;<br><br>    public void setId(Long id) {<br>        this.id = id;<br>    }<br><br>    public Long getId() {<br>        return id;<br>    }<br><br>    public Long getUserId() {<br>        return userId;<br>    }<br><br>    public void setUserId(Long userId) {<br>        this.userId = userId;<br>    }<br><br>    public Long getProductId() {<br>        return productId;<br>    }<br><br>    public void setProductId(Long productId) {<br>        this.productId = productId;<br>    }<br><br>    public Integer getQuantity() {<br>        return quantity;<br>    }<br><br>    public void setQuantity(Integer quantity) {<br>        this.quantity = quantity;<br>    }<br><br>    public Double getTotalPrice() {<br>        return totalPrice;<br>    }<br><br>    public void setTotalPrice(Double totalPrice) {<br>        this.totalPrice = totalPrice;<br>    }<br>}</pre><p><em>Create OrderRepository</em></p><pre>@Repository<br>public interface OrderRepository extends JpaRepository&lt;Order,Long&gt; {<br>}</pre><p>Next, I have created the <em>Order Service</em> and implemented the core functionality to handle order creation and fetch order details.</p><pre>@Service<br>public class OrderService {<br>    private final OrderRepository orderRepository;     <br><br>    public OrderService(OrderRepository orderRepository) {<br>        this.orderRepository = orderRepository;        <br>    }<br><br>    public CommonResponse createOrderService(Order order) {<br>        CommonResponse response = new CommonResponse();<br>        try {<br>            Order createdOrder = orderRepository.save(order);<br>            response.setStatus(1);<br>            response.setNarration(&quot;Order created successfully orderId: &quot; + createdOrder.getId());<br>        } catch (Exception exception) {<br>            response.setStatus(-1);<br>            response.setNarration(&quot;Order creation failed&quot;);<br>        }<br>        return response;<br>    }<br><br>    public List&lt;Order&gt; getAllOrders() {        <br>        return orderRepository.findAll();<br>    }<br>}</pre><p>Once the service layer is done, the next step is to expose its functionalities as RESTful APIs. For this, create the <strong>OrderController</strong> class. This controller handles HTTP requests related to order operations.</p><pre>@RestController<br>@RequestMapping(&quot;/orders&quot;)<br>public class OrderController {<br><br>    private final OrderService orderService;<br><br>    public OrderController(OrderService orderService) {<br>        this.orderService = orderService;<br>    }<br><br>    @PostMapping(&quot;/manualOrder&quot;)<br>    public CommonResponse createOrder(@RequestBody Order order){<br>        return orderService.createOrderService(order);<br>    }<br><br>    @GetMapping(&quot;/getOrders&quot;)<br>    public List&lt;Order&gt; getAllOrders() {<br>        return orderService.getAllOrders();<br>    }<br>}</pre><p>Run the Order service application. Once you refresh the Eureka dashboard on <a href="http://localhost:8761/">http://localhost:8761/</a> , you can now see the order-service is available under available instances as below</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/992/1*l-UAM2p28Dk6BhoWU1xnNg.png" /><figcaption>Order service registered with Eureka server</figcaption></figure><p>Then, check the order service endpoints using Postman</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6rg9S7-WIkFjwCZO1VSsnw.png" /><figcaption>Order creation API testing</figcaption></figure><p>Next, create our second microservice</p><h4><strong>Product Service</strong></h4><p>This service handles operations related to product data, such as adding new products and retrieving product details. Register itself with the Eureka server and expose APIs to manage product data with <strong>its own</strong> MySQL database</p><p>As earlier, create a Spring Boot application with relevant dependencies and register the Product service with Eureka</p><pre>spring.application.name=product-service<br>server.port=8081<br><br>spring.datasource.url=jdbc:mysql://localhost:3306/productdb<br>spring.datasource.username=root<br>spring.datasource.password=password<br><br>spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver<br><br>spring.jpa.hibernate.ddl-auto=update<br>spring.jpa.show-sql=true<br>spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.MySQL8Dialect<br><br>eureka.client.register-with-eureka=true<br>eureka.client.fetch-registry=true<br>eureka.client.service-url.defaultZone=http://localhost:8761/eureka/<br>eureka.instance.prefer-ip-address=true<br>eureka.instance.ip-address=127.0.0.1</pre><pre>@SpringBootApplication<br>@EnableDiscoveryClient<br>public class ProductServerApplication {<br><br> public static void main(String[] args) {<br>  SpringApplication.run(ProductServerApplication.class, args);<br> }<br>}</pre><p><em>Create Product Entity</em></p><pre>@Entity<br>@Table (name = &quot;products&quot;)<br>public class Product {<br><br>    @Id<br>    @GeneratedValue (strategy = GenerationType.IDENTITY)<br>    private Long id;<br><br>    private String name;<br><br>    private String description;<br><br>    private Double price;<br><br>    private Integer stockQuantity;<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>    public Double getPrice() {<br>        return price;<br>    }<br><br>    public void setPrice(Double price) {<br>        this.price = price;<br>    }<br><br>    public Integer getStockQuantity() {<br>        return stockQuantity;<br>    }<br><br>    public void setStockQuantity(Integer stockQuantity) {<br>        this.stockQuantity = stockQuantity;<br>    }<br>}</pre><p><em>Product repository</em> as below</p><pre>@Repository<br>public interface ProductRepository extends JpaRepository&lt;Product,Long&gt; {<br>}<br></pre><p>Create<em> Product service</em></p><pre>@Service<br>public class ProductService {<br>    private ProductRepository productRepository;<br>    <br>    public ProductService(ProductRepository productRepository) {<br>        this.productRepository = productRepository;<br>    }<br><br>    public CommonResponse createProductService(Product productRequest){      <br>        CommonResponse response = new CommonResponse();<br>        try {<br>            Product createdProduct =  productRepository.save(productRequest);<br>            response.setStatus(1);<br>            response.setNarration(&quot;Product created successfully productId: &quot; + createdProduct.getId());<br>        } catch (Exception exception) {<br>            response.setStatus(-1);<br>            response.setNarration(&quot;Product creation failed&quot;);<br>        }<br>        return response;<br>    }<br><br>    public Product getProductById(long id){<br>        return productRepository.findById(id).orElseThrow(() -&gt; new RuntimeException(&quot;Product not found&quot;));<br>    }<br>}</pre><p>Then create <em>Product Controller</em></p><pre>@RestController<br>@RequestMapping(&quot;/products&quot;)<br>public class ProductController {<br><br>    private final ProductService productService;<br><br>    @Autowired<br>    public ProductController(ProductService productService) {<br>        this.productService = productService;<br>    }<br><br>    @PostMapping<br>    public CommonResponse createProduct(@RequestBody Product product) {<br>        return productService.createProductService(product);<br>    }<br>    @GetMapping (&quot;/{id}&quot;)<br>    public Product getProductById(@PathVariable Long id) {<br>        return productService.getProductById(id);<br>    }<br>}</pre><p>Then, make sure to create a separate database for the Product service also. Now run your product service, and it will be visible on the Eureka server dashboard as below</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/987/1*jK3OE_C38IjA8JH_IiodQg.png" /><figcaption>Product Service registered with Eureka</figcaption></figure><p>Let’s check the endpoints for confirmation</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*C-QsLUVxhhmV1rJYPccOzg.png" /><figcaption>Product cretaion API testing</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gZ-_s07Qq4I0LnrZ5awU-g.png" /><figcaption>Get product by product id API testing</figcaption></figure><h4>API Gateway — The Central Entry Point🎯</h4><p>Now we have successfully developed two microservices and registered them in the Eureka server. But when we consider real-world microservices systems, the number of services is high. Then managing communication between clients and services becomes complex and inefficient. Without a central entry point, <strong>clients must know the network location (IP, port, URI paths) of each individual service</strong> they want to communicate with. In a microservices architecture, instead of exposing all services to the external world, an API Gateway is used as a central entry point. It routes incoming HTTP requests to the appropriate microservice and can handle cross-cutting concerns like security and logging.</p><p>So, let&#39;s build an API gateway for our E-commerce project also</p><p>Create a Spring Boot project with the following dependencies</p><pre>&lt;dependencies&gt;<br>&lt;dependency&gt;<br>   &lt;groupId&gt;org.springframework.cloud&lt;/groupId&gt;<br>   &lt;artifactId&gt;spring-cloud-starter-gateway&lt;/artifactId&gt;<br>  &lt;/dependency&gt;<br>  &lt;dependency&gt;<br>   &lt;groupId&gt;org.springframework.cloud&lt;/groupId&gt;<br>   &lt;artifactId&gt;spring-cloud-starter-netflix-eureka-client&lt;/artifactId&gt;<br>  &lt;/dependency&gt;<br>&lt;/dependencies&gt;</pre><p>Annotate your ApiGatewayApplication class with @EnableDiscoveryClient to integrate it with the service discovery mechanism.</p><pre>@SpringBootApplication<br>@EnableDiscoveryClient<br>public class ApiGatewayApplication {<br> public static void main(String[] args) {<br>  SpringApplication.run(ApiGatewayApplication.class, args);<br> }<br>}</pre><p>Then, configure the application.yml file as follows</p><pre>server:<br>  port: 8083<br><br>spring:<br>  application:<br>    name: api-gateway<br><br>  cloud:<br>    gateway:<br>      routes:<br>        - id: product-service<br>          uri: lb://product-service<br>          predicates:<br>            - Path=/product-service/**<br><br><br>        - id: order-service<br>          uri: lb://order-service<br>          predicates:<br>            - Path=/order-service/**<br><br>      discovery:<br>        locator:<br>          enabled: true<br>          lower-case-service-id: true<br><br>eureka:<br>  client:<br>    register-with-eureka: true<br>    fetch-registry: true<br>    service-url:<br>      defaultZone: http://localhost:8761/eureka/</pre><ul><li><strong>id:</strong> A unique identifier for the route. This is mainly used for logging purposes.</li><li><strong>uri:</strong> The destination where the request should be forwarded.</li><li>The lb:// prefix stands for <strong>LoadBalancer</strong>, meaning API Gateway will use <strong>service discovery </strong>to dynamically resolve the actual instances of the service.</li><li>lb://product-service refers to the <strong>Product Service</strong> as registered in the service registry.</li><li><strong>predicates:</strong> Defines the conditions that incoming requests must match for the route to be applied.</li><li>Path=/product-service/**: This means that any request path starting with /product-service/ will be routed to the <strong>Product Service</strong>.</li><li>Similarly, /order-service/** routes will be forwarded to the <strong>Order Service</strong>.</li><li><strong>enabled: true</strong><br> This allows the API Gateway to automatically create routes for all services registered in the service discovery server.</li><li><strong>lower-case-service-id: true</strong><br> Converts the service IDs to lowercase when creating routes.</li></ul><p>Now we are going to test the endpoints via the API gateway call</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LfLcQAGC5RXJ0OFN1kiQCg.png" /><figcaption>API Gateway call to Create product endpoint</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5x6VOa_vSeniflWh8vf2uA.png" /><figcaption>API gateway call to Get product by id endpoint</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jI6vYQaIHkkoExf5G4uQ-A.png" /><figcaption>API Gateway call to create order endpoint</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CKa40hA5w27iAJoX7w9d4g.png" /><figcaption>API gateway call to Retrieve all orders end point</figcaption></figure><p><strong>In this project our API Gateway,</strong></p><ul><li>Routes API requests to the Order service and the Product service</li><li>Dynamically discovers services using Eureka</li><li>Acts as a single point of entry for external clients</li></ul><p>Apart from that, there are some other features that an API Gateway does. You can use the following article to get to know more about the features of an API gateway</p><p><a href="https://medium.com/@ankithahjpgowda/api-gateway-in-spring-boot-3ea804003021">API gateway in Spring boot</a></p><p>Now let’s go through our project&#39;s overall flow</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/608/1*LmIRpo_tieBu97YLF2sYkA.png" /><figcaption><em>Architectural diagram</em></figcaption></figure><ol><li>The client sends a request → API Gateway</li><li>API Gateway routes the request → Order Service or Product Service</li><li>Each service registers itself with Eureka, so the gateway knows where to route</li></ol><p>🚀<strong>What’s Next?</strong></p><p>Although this project covers the fundamental concepts of microservices architecture using Spring Boot, here are a few ideas for how this project can be taken to the next level</p><ul><li><strong>Inter-service Communication with OpenFeign — </strong>When placing an order, it’s important to first check whether the requested product quantity is available. To do this, the <strong>Order Service</strong> needs to communicate with the <strong>Product Service</strong>. This is where <strong>OpenFeign</strong> becomes extremely useful. Instead of writing verbose and repetitive HTTP client code, OpenFeign allows you to define a simple Java interface to represent the remote call. It takes care of the underlying HTTP communication for you. As a declarative HTTP client, OpenFeign integrates smoothly with <strong>Spring Cloud</strong>, making inter-service communication more efficient and readable. Since we have used the service registry, the order service can call the product service by using its registered name. You can find the source code for this scenario in my Git repository, that have attached at the end of this blog.</li><li><strong>Add Role-Based Authentication with JWT — </strong>Secure your services using <strong>Spring Security</strong> and <strong>JWT (JSON Web Tokens)</strong>. You can define different roles, like ADMIN and CUSTOMER and restrict access to specific endpoints based on those roles. This is a crucial part of real-world microservices.</li><li><strong>Introduce Asynchronous Messaging (Kafka or RabbitMQ) — </strong>In real-world systems, services should be loosely coupled. Instead of the Order Service calling the Product Service directly to update stock, you can use <strong>Kafka or RabbitMQ </strong>to send a message after an order is placed. The Product Service listens to this message and updates the inventory.</li><li><strong>Dockerize the Entire Application — </strong>Package each service into a <strong>Docker container</strong> and use <strong>Docker Compose</strong> to run the full microservices system with a single command. This can be used to deploy the app on cloud platforms.</li></ul><p><strong>Wrapping Up🔚</strong></p><p>Transitioning from monolithic architecture to microservices may seem overwhelming at first, but as you’ve seen through this example project, the shift can start small and still provide immense value. Microservices offer <strong>flexibility</strong>, <strong>scalability</strong>, and <strong>modularity </strong>helping you build systems that are easier to maintain and evolve over time.</p><p>I hope this guide helps you understand the service registration, communication, and gateway routing while turning concepts into code. You can refer full code of this project on this <a href="https://github.com/devindianushika/e-com">Git repository</a></p><p>So why wait❓<br>Start small, experiment, and <strong>transform your monolithic applications into modern, cloud-ready microservices</strong> today</p><p>Thanks for reading! If you found this helpful, feel free to leave a clap👏</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3364577bc305" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Language Processing with Python]]></title>
            <link>https://ai.plainenglish.io/language-processing-with-python-9e99590ed1d0?source=rss-82c5800e623------2</link>
            <guid isPermaLink="false">https://medium.com/p/9e99590ed1d0</guid>
            <category><![CDATA[nlp]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[lemmatization]]></category>
            <category><![CDATA[natural-language-process]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Devindi Jayathilaka]]></dc:creator>
            <pubDate>Sat, 10 Jul 2021 13:15:30 GMT</pubDate>
            <atom:updated>2021-09-10T09:11:34.043Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Z6zAl26xaV-UlfVA" /><figcaption>Photo by <a href="https://unsplash.com/@sincerelymedia?utm_source=medium&amp;utm_medium=referral">Sincerely Media</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>As you know, Natural language processing plays a big role in today&#39;s modern technology. Language can be in a list of individual words, sentences, multiple paragraphs with special characters. Due to the complexity of natural language, we need to do some language processing tasks before they apply to the applications. Here I discuss the following topics under language processing.</p><ol><li>Tokenizing text</li><li>Stop Word Elimination</li><li>Stemming</li><li>Lemmatizing</li><li>POS Tagging</li></ol><h4><strong>1.Tokenizing text</strong></h4><p>Tokenizing is the task of breaking text into sentences or words. A word is a token in a sentence and a sentence is a token of a paragraph. Therefore I divide it into two subparts as <strong>Word tokenization</strong> and <strong>Sentence tokenization.</strong></p><p>First, let’s see sentence tokenization in python. To do that I import<strong> </strong>the<strong> </strong>sentence tokenization function.<strong> </strong>Then call it with the target paragraph as an argument.</p><pre>paragraph = &quot;Good afternoon all. It&#39;s good to see you. Welcome to the Natural Language Processing practical session.&quot;</pre><pre>from nltk.tokenize import sent_tokenize<br>sent_tokenize(paragraph )</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/643/1*65drkjtwVHCgfptJvTrgFQ.png" /><figcaption>Screenshot by the Author</figcaption></figure><p>Unlike sentence tokenization, word tokenization can be done in several methods.</p><p><strong>Using word_tokenize() : </strong>word_tokenize() is a commonly used function. It’s a pre-built function in NLTK.</p><pre>from nltk.tokenize import word_tokenize<br>word_tokenize(&#39;Hello Everyone.&#39;)</pre><p><strong>Using</strong> <strong>Regular-Expression Tokenizers: </strong>Word tokenizing using regular expressions is another method. It uses white space as delimiter. I assume you might have a basic understanding of regular expressions. If not please follow <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions">this</a>.</p><pre>from nltk.tokenize import RegexpTokenizer<br>tokenizer = RegexpTokenizer(&quot;[\w&#39;]+&quot;)<br>tokenizer.tokenize(&quot;Can&#39;t is a contraction.&quot;)</pre><p>Another pattern which use to identify gaps to tokenize sentences.</p><pre>from nltk.tokenize import RegexpTokenizer<br>tokenizer = RegexpTokenizer(&#39;\s+&#39;, gaps=True)<br>tokenizer.tokenize(&quot;Can&#39;t is a contraction.&quot;)</pre><p><strong>Using WordPunctTokenizer(): </strong>Using this method, split the words on punctuations.</p><pre>from nltk.tokenize import WordPunctTokenizer<br>tokenizer = WordPunctTokenizer()<br>tokenizer.tokenize(&quot;Can&#39;t is a contraction.&quot;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/376/1*IhbD-3bRlk60JtVAoWopfg.png" /><figcaption>Screenshot by the Author</figcaption></figure><p><strong>Using</strong> <strong>TweetTokenizer</strong>(): This method used to tokenize Twitter data</p><pre>from nltk.tokenize import TweetTokenizer<br>tknzr = TweetTokenizer()<br>s0 = &quot;This is a cooool #dummysmiley: :-) :-P &lt;3 and some arrows &lt; &gt; -&gt; &lt;--&quot;<br>tknzr.tokenize(s0)</pre><h4><strong>2. Stop Word Elimination</strong></h4><p>Real word text contains a lot of words. But that all the words do not carry important meaning. The words which do not convey any meaning are called stop words. We need to remove those words from our corpus. Then we can focus on the important keywords only. NLTK comes with a stopwords corpus that contains word lists for many languages. Otherwise, you can build your own stop words file.</p><pre>from nltk.corpus import stopwords<br>stop = stopwords.words(&#39;english&#39;)<br>df[&#39;text&#39;].apply(lambda x: &quot; &quot;.join(x for x in x.split() if x not in stop))</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/433/1*ww97sl1JsQTR_SvH3bB9zg.png" /><figcaption>Screenshot by the Author</figcaption></figure><h4><strong>3. Stemming</strong></h4><p>Stemming is the process of converting derived words into their root words. For example words like ‘writing’, ‘wrote’, ‘written’ are reduced to the base form ‘write’.I use my previously processed text list as the corpus here also. You can see that some words are stemmed into their root word as below image.</p><pre>from nltk.stem import PorterStemmer<br>st = PorterStemmer()<br>df[&#39;text&#39;].apply(lambda x: &quot; &quot;.join([st.stem(word) for word in x.split()]))</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/422/1*TOSxSDEjMPc_EWug6awqFw.png" /><figcaption>Screenshot by the Author</figcaption></figure><h4><strong>4. Lemmatizing</strong></h4><p>Lemmatizing is the process of extracting the root word by considering vocabulary. Actually, stemming also gives root word but it does not consider the context of the word. That is <strong>the difference between stemming and lemmatizing</strong>. For example, ‘good’, ‘better’, ‘best’ is lemmatized into good.</p><p>There are different python packages to do lemmatization. I use Wordnet Lemmatizer with NLTK. <strong>WordNet</strong> is a lexical database of the English language introduced by the Princeton University. It consists of nouns, verbs, adjectives, and many more with semantic relations. You can know more about WordNet by the following site.</p><p><a href="https://wordnet.princeton.edu/">WordNet</a></p><p>Since I lemmatize a list of sentences, I need to do word tokenizing before proceed.</p><pre>#Word tokenizing<br>import nltk<br>from nltk.tokenize import word_tokenize<br><br>corpus =[&#39;I like fishing&#39;,&#39;I eat fish&#39;,&#39;There are many fishes in pound&#39;, &#39;leaves and leaf&#39;]<br>df = pd.DataFrame({&#39;text&#39;: corpus})</pre><pre>text_list = df[&quot;text&quot;].tolist()<br>listToStr = &#39; &#39;.join(map(str,text_list))<br>word_list = nltk.word_tokenize(listToStr)</pre><pre># Init the Wordnet Lemmatizer<br>from nltk.stem import WordNetLemmatizer <br>lemmatizer = WordNetLemmatizer()</pre><pre># Lemmatize list of words and join<br>lemmatized_output = &#39; &#39;.join([lemmatizer.lemmatize(w) for w in word_list])<br>print(lemmatized_output)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/709/1*OEujHykA9ls4Sbeogr-siw.png" /><figcaption>Screenshot by the Author</figcaption></figure><p>You can see that the words ‘fishing’ ‘fishes’ are lemmatized into ‘fish’.And word ‘leaves’ is lemmatized into ‘leaf’.</p><h4><strong>5. POS Tagging</strong></h4><p><strong>P</strong>art <strong>O</strong>f <strong>S</strong>peech Tagging is the process of assigning part of speech tag to each word in a sentence. It is an important task in text processing since it gives significant information about the word. It’s an initial part of syntactic analysis. Basically, it is used in Words sense Disambiguation, Named entity recognition, Sentiment Analysis, Question Answering, etc. Here’s a list of the tags and what they mean.</p><p><strong>♦ CC</strong> coordinating conjunction</p><p><strong>♦ CD</strong> cardinal digit</p><p><strong>♦ DT</strong> determiner</p><p><strong>♦ EX</strong> existential there (like: “there is” … think of it like “there exists”)</p><p><strong>♦ FW</strong> foreign word</p><p><strong>♦ IN</strong> preposition/subordinating conjunction</p><p><strong>♦ JJ</strong> adjective ‘big’</p><p><strong>♦ JJR</strong> adjective, comparative ‘bigger’</p><p><strong>♦ JJS</strong> adjective, superlative ‘biggest’</p><p><strong>♦ LS</strong> list marker 1)</p><p><strong>♦ MD</strong> modal could, will</p><p><strong>♦ NN</strong> noun, singular ‘desk’</p><p><strong>♦ NNS</strong> noun plural ‘desks’</p><p>Furthermore, refer to the following guide</p><p><a href="https://www.ling.upenn.edu/courses/Fall_2003/ling001/penn_treebank_pos.html">Penn Treebank P.O.S. Tags</a></p><p>I use the NLTK pos tagging module to assign POS tags for my corpus. Since my corpus is a paragraph, I do the sentence tokenizing and then do the word tokenizing to generate POS tags.</p><pre>from nltk.corpus import stopwords<br>from nltk.tokenize import word_tokenize, sent_tokenize<br>stop_words = set(stopwords.words(&#39;english&#39;))<br>corpus =&quot;I love NLP and I will learn NLP in 2 month.It is an interesting subject&quot;</pre><pre># Sentence tokenizing<br>tokens = sent_tokenize(corpus)<br>#Word tokenizing and assign tagging <br>for i in tokens:<br>    words = nltk.word_tokenize(i) <br>    words = [w for w in words if not w in stop_words] <br>    #  POS-tagger.  <br>    tags = nltk.pos_tag(words)<br>    print(tags)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*K12RjvWm7Wvt6TbF6O0PAw.png" /><figcaption>Screenshot by the Author</figcaption></figure><p>The output shows the assigned POS tags for each word.</p><p>Thanks for reading. I hope this was helpful. If you have any questions, feel free to leave a response.</p><p>Happy Coding!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9e99590ed1d0" width="1" height="1" alt=""><hr><p><a href="https://ai.plainenglish.io/language-processing-with-python-9e99590ed1d0">Language Processing with Python</a> was originally published in <a href="https://ai.plainenglish.io/">Artificial Intelligence in Plain English</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Understanding Data Cleaning]]></title>
            <link>https://medium.com/linkit-intecs/understanding-data-cleaning-4f3b39536c98?source=rss-82c5800e623------2</link>
            <guid isPermaLink="false">https://medium.com/p/4f3b39536c98</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[preprocesing]]></category>
            <dc:creator><![CDATA[Devindi Jayathilaka]]></dc:creator>
            <pubDate>Sun, 13 Jun 2021 08:34:15 GMT</pubDate>
            <atom:updated>2021-06-13T08:34:15.993Z</atom:updated>
            <content:encoded><![CDATA[<h4>An Introduction to Data Cleaning Using Python</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*ShrhYnWC_-TcafJF" /><figcaption>Photo by <a href="https://unsplash.com/@emilymorter?utm_source=medium&amp;utm_medium=referral">Emily Morter</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Hello everyone😊</p><p>Why do we do data preprocessing? Actually, this is a simple question for those who are familiar with data science technologies, but this short guide will help improve knowledge for them as well as those who are new to data science.</p><p>There are different ways to collect data such as using APIs, Reading documents, Web scraping, etc. But this real-world data is dirty. They consist of noisy data with incorrect values, incomplete data, inconsistent data, and duplicate values. Therefore it is necessary to do data preprocessing to have good quality data set.</p><p>Major tasks of data preprocessing are,</p><p><strong>1. Data</strong> <strong>Cleaning — </strong>Fill in missing values, smooth noisy data, identify or remove outliers, and resolve inconsistencies</p><p><strong>2. Data</strong> <strong>Integration — </strong>Combines data from multiple sources into a coherent store</p><p><strong>3. Data</strong> <strong>Transformation — </strong>Normalization and aggregation of data</p><p><strong>4. Data</strong> <strong>Reduction — </strong>Obtains reduced representation in volume but produces the same or similar analytical results</p><p>In this article, I am going to explain more about Data cleaning and how it uses Python.</p><p>OK let’s go forward…</p><p>At the initial step of data preprocessing, data cleaning is done by filling missing values, identifying outliers, smoothing out noisy data, and correcting inconsistent data. Also, data cleaning checks and makes sure that all data is in the correct data format (int, float, text, or other).</p><h4>How Can We Identify Missing Values in a Data Set?</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/418/1*H7c1nhD9XnpB5ybFC80eNg.png" /><figcaption><strong><em>Screenshot by Author — Glimpse of noisy data</em></strong></figcaption></figure><p>In the above image, data that appear in several question marks are the missing values. We can replace “?” with NaN (Not a Number) as follows. Let’s see how we do it using Python.</p><pre>import pandas as pd<br>import numpy as np</pre><pre>df = pd.read_csv(&quot;auto_data.csv&quot;)<br>df.replace(&quot;?&quot;, np.nan, inplace = True)<br>df.head()</pre><p>You can see the output as follows.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/412/1*1t_lOfLH_3qP6cETzCxgsA.png" /><figcaption><strong><em>Screenshot by Author — After marking missing values as NaN</em></strong></figcaption></figure><p>Also, Python’s built-in functions <strong>isnull() </strong>and <strong>notnull() </strong>use<strong> </strong>to identify these missing values. <strong>isnull()</strong> identify existing missing values<strong> </strong>while <strong>notnull()</strong> function detects existing non-missing values in the data frame.</p><h4>How to Deal With Missing Data?</h4><p>Now you may have a question about how do we do further data analyzing tasks with these missing values? There are different methods you can apply as appropriate to your data frame.</p><ol><li>drop data<br> a. drop the whole row<br> b. drop the whole column</li></ol><p>If most entries in a column are empty, you can drop the whole column. And if there any raw without data that is not useful to our data analysis task, we can drop that raw also. Otherwise, you can replace those missing values. Here you have the freedom to choose the most suitable method for replacing according to your data frame.</p><p>2. replace data<br> a. replace it by mean<br> b. replace it by frequency</p><p>Let’s see how to replace missing values by mean using python. First of all, you need to calculate the average value of particular data. Here, I calculate the mean value for the “normalized-losses” column in my data set. Then replace NaN values using the calculated mean value.</p><pre>avg_norm_loss = df[&quot;normalized-losses&quot;].astype(&quot;float&quot;).mean()<br>print(&quot;Average value of normalized-losses :&quot;, avg_norm_loss)<br>df[&quot;normalized-losses&quot;].replace(np.nan, avg_norm_loss, inplace=True)<br></pre><p>I got the average of normalized losses as 122 and output as follows when after replaced.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/392/1*Lg6K_A1DhmKtvxRF_4H-Aw.png" /><figcaption><strong><em>Screenshot by Author</em></strong></figcaption></figure><p>Replacement by the most frequent value in the data set is another method. To do that you can use <strong>value counts()</strong> or <strong>idxmax()</strong> functions in Python DataFrame.</p><pre>df[&#39;num-of-doors&#39;].value_counts()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/329/1*LhyoVkiYHlzqkQKsh_kGSA.png" /><figcaption><strong><em>Screenshot by Author</em></strong></figcaption></figure><p>You can see four doors are the most frequent door type in this data set. So we can replace missing values in that data column by four.</p><pre>df[&quot;num-of-doors&quot;].replace(np.nan, &quot;four&quot;, inplace=True)</pre><p>Then if you have data which are not incorrect data format, you can convert it to the proper data type at this data cleaning part. Numerical variables should have type “float” or “int”, and variables with strings such as categories should have the type “object”.</p><pre>df[[&quot;bore&quot;, &quot;stroke&quot;, &quot;peak-rpm&quot;,&quot;price&quot;]] = df[[&quot;bore&quot;,&quot;stroke&quot;,&quot;peak-rpm&quot;,&quot;price&quot;]].astype(&quot;float&quot;)</pre><pre>df[[&quot;normalized-losses&quot;]] = df[[&quot;normalized-losses&quot;]].astype(&quot;int&quot;)</pre><p>Finally, you can obtain cleaned data set without missing values and all data in its proper format.</p><p>Thanks for reading. I hope this was helpful. If you have any questions, feel free to leave a response.</p><p>Happy Coding!!!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4f3b39536c98" width="1" height="1" alt=""><hr><p><a href="https://medium.com/linkit-intecs/understanding-data-cleaning-4f3b39536c98">Understanding Data Cleaning</a> was originally published in <a href="https://medium.com/linkit-intecs">LinkIT</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How Does a Machine Understand Text or Speech?]]></title>
            <link>https://python.plainenglish.io/converting-text-to-features-90f0708efdd2?source=rss-82c5800e623------2</link>
            <guid isPermaLink="false">https://medium.com/p/90f0708efdd2</guid>
            <category><![CDATA[nlp]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[Devindi Jayathilaka]]></dc:creator>
            <pubDate>Sun, 06 Jun 2021 10:20:35 GMT</pubDate>
            <atom:updated>2021-07-17T21:17:15.775Z</atom:updated>
            <content:encoded><![CDATA[<h4>Convert Text to Features using TF-IDF</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*laQfGRCuUN37rywE" /><figcaption>Photo by <a href="https://unsplash.com/@waldemarbrandt67w?utm_source=medium&amp;utm_medium=referral">Waldemar Brandt</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h4>How can a machine understand what we talk or what we write?</h4><p>As we already know, it cannot understand our words or sentences except numbers. So, we should make unstructured, noisy data to interact with machines.</p><p>Converting text data into a machine-understandable format (that means numbers) is called feature engineering of text data. Different types of feature engineering methods are used in the industry. Machine learning algorithm’s performance and accuracy depend on the feature engineering technique you used. This guide helps you to understand the TF-IDF technique of feature engineering.</p><h4>What is TF-IDF?</h4><p><strong>TF</strong> means <strong>Term frequency</strong> while <strong>IDF</strong> means <strong>Inverse Document frequency.</strong> Term Frequency gives us a ratio of the frequency of a word in a sentence, to the length of the sentence.</p><p>Inverse Document Frequency of a word is the log of the ratio of the total number of sentences to the number of sentences in a particular document in which that word is present. It gives how important a word is to a document in a corpus. Normally, words that occur rarely in the corpus have a high IDF score.</p><p>The product of TF and IDF value is called the TF-IDF score of a word.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/853/1*5hsNzl4afCbeHHa1MrFufg.png" /><figcaption>TF — IDF formula</figcaption></figure><p>It gives an idea of how often a word occurs in a document as well as in the entire corpus. Words that are more common in one sentence and less common in other sentences should be given high weights.</p><p>Let’s see how we can easily code the TF-IDF technique using python. The <strong>scikit-learn library</strong> in python makes it easy for us.</p><p>First, need to import TfidfVectorizer as follows</p><pre>from sklearn.feature_extraction.text import TfidfVectorizer</pre><p>Then I make a simple corpus that includes few sentences.</p><pre>Text = [“The quick brown fox jumped over the lazy dog.”, “The    dog.”,”The fox”]</pre><p>Next, initialize the vectorizer and then call the function to fit and transform our corpus over it to calculate the TF-IDF score for the text.</p><pre>vectorizer = TfidfVectorizer()<br>response = vectorizer.fit_transform(Text)<br>print(response)</pre><p>It will result following output.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/436/1*PfV8Rj90JOhZVYMZsK-hfw.png" /><figcaption>Screenshot by the Author</figcaption></figure><p>Note that it will give a <a href="https://www.geeksforgeeks.org/sparse-matrix-representation/">sparse matrix</a> that contains document id, token id, and the TF-IDF value. If you want to see the features of the above corpus run the below command.</p><pre>vectorizer.get_feature_names()</pre><p>To more functions in <strong>scikit-learn</strong> feature extraction refer to the below site.</p><p><a href="https://scikit-learn.org/stable/modules/generated/sklearn.feature_extraction.text.TfidfVectorizer.html">sklearn.feature_extraction.text.TfidfVectorizer</a></p><p>Thanks for reading this article. Let’s meet with another lesson in the near future. Happy Coding!</p><p><em>More content at </em><a href="http://plainenglish.io/"><strong><em>plainenglish.io</em></strong></a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=90f0708efdd2" width="1" height="1" alt=""><hr><p><a href="https://python.plainenglish.io/converting-text-to-features-90f0708efdd2">How Does a Machine Understand Text or Speech?</a> was originally published in <a href="https://python.plainenglish.io/">Python in Plain English</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Connect your Node.js server with Mongo DB]]></title>
            <link>https://medium.com/swlh/connect-your-node-js-server-with-mongo-db-e478f6efc227?source=rss-82c5800e623------2</link>
            <guid isPermaLink="false">https://medium.com/p/e478f6efc227</guid>
            <category><![CDATA[mongodb]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Devindi Jayathilaka]]></dc:creator>
            <pubDate>Thu, 21 May 2020 09:46:43 GMT</pubDate>
            <atom:updated>2021-06-05T04:59:39.362Z</atom:updated>
            <content:encoded><![CDATA[<h3>Connect Your Node.js Server With Mongo DB</h3><h4>CRUD Operations Using Node.js and Mongo DB</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*xW1vOGrCzwI5rZb1" /><figcaption>Photo by <a href="https://unsplash.com/@kevnbhagat?utm_source=medium&amp;utm_medium=referral">Kevin Bhagat</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Hi, everyone!!! Welcome back again</p><p>Let’s talk about how to connect your node server with MongoDB and develop CRUD operations. You can refer my <a href="https://medium.com/linkit-intecs/introduction-to-building-a-nodejs-server-92ce5cba00fb">previous article</a> and build your Node server first. For further developments, you need to do some installations. First, download and install MongoDB on your machine.</p><p><a href="https://www.mongodb.com/download-center/community">MongoDB Community Download</a></p><p>Then come back to your <strong>app.js</strong> file. Here, we will import <a href="https://mongoosejs.com/"><strong>Mongoose</strong></a><strong> </strong>to connect our database with the server. Mongoose used to define database schema as objects. You can know more about Mongoose by the following site.</p><p><a href="https://mongoosejs.com/">Mongoose</a></p><p>Install mongoose by using</p><pre>npm install mongoose</pre><p>Then require mongoose in <strong>app.js </strong>file</p><pre>const mongoose = require(&#39;mongoose&#39;);</pre><p>Make sure you run the Mongo server now. Here <strong>27017</strong> is the default port of Mongo.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RE6l5FrEE2FXZdDRnWgckA.png" /><figcaption>Mongo server — Screenshot By Author</figcaption></figure><p>To do the following configurations make <strong>database.js</strong> file in the config folder. Give the default port of Mongo server as I mentioned before and the name of the database. Make sure to export the file also.</p><pre>module.exports = {</pre><pre>&quot;database&quot;:&quot;mongodb://localhost:27017/authapp&quot;</pre><pre>}</pre><p>To access the configurations import it in your <strong>app.js</strong> file and make the connection correctly. Furthermore, you can make conditions as you like to establish your connection.</p><pre>const express = require (&#39;express&#39;);<br>const app = express();<br>const port = 3000;<br>const mongoose = require(&#39;mongoose&#39;);<br>const config = require (&#39;./config/database&#39;);<br>const connection = mongoose.connect(config.database, {<br>  useNewUrlParser: true, useUnifiedTopology: true });</pre><pre>if(connection){<br>console.log(&quot;database connected&quot;);<br>}</pre><pre>else{<br>console.log(&quot;database connection error&quot;);<br>}</pre><pre>app.get(&quot;/&quot;,function(req,res){<br>    res.end(&quot;hello world&quot;);<br>})<br>app.listen(port,function(){<br>    console.log(&quot;server is &quot; + port);</pre><pre>});</pre><p>Ok now run the node server, you can see the following output on your terminal if your database connected successfully.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/683/1*SEqumBX-0BLhWzQpDujdKA.png" /><figcaption>screenshot by Author</figcaption></figure><p>Let’s move on. Its time to build main CRUD operations as following</p><p><strong>C</strong>reate user data</p><p><strong>R</strong>etrieve user data</p><p><strong>U</strong>pdate user data</p><p><strong>D</strong>elete user data</p><h3>Create user data</h3><p>Here you need to make a <strong>schema </strong>that represents the fields and data types of the database. Make a new file<strong> user.js</strong> under the models folder. Then do the following steps in that file.</p><ol><li>require mongoose</li><li>Load the <strong>schema</strong> module</li><li>Make a new object of <strong>schema </strong>and give a name (Here my schema name is <strong>user schema</strong>)</li><li>Inside your schema defines fields of your collection and their data types</li><li>Export the <strong>schema</strong></li></ol><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8bf82284d46fb5a9481d0cb02c596f6f/href">https://medium.com/media/8bf82284d46fb5a9481d0cb02c596f6f/href</a></iframe><p>To do all routes clearly, it&#39;s better to use another file other than using the <strong>app.js </strong>file. Therefore make <strong>routeuser.js</strong> file under the routes folder. Define the express router module and also the <strong>user.js </strong>file.</p><p>Here our data send as the<strong> </strong><a href="https://www.w3schools.com/whatis/whatis_json.asp"><strong>JSON </strong></a>type data in the request body. Therefore it is required to install <a href="https://github.com/expressjs/body-parser"><strong>body-parser</strong></a><strong> </strong>which is a Nodejs middleware to handle from data and define it in <strong>app.js</strong> file</p><pre>npm install body-parser</pre><p>Now make your POST request in <strong>routeuser.js</strong> file with suitable endpoint and call back function. And save your request body data by making a new user object.</p><pre>router.post(&quot;/register&quot;, (req, res) =&gt; {</pre><pre>const newUser = new User({</pre><pre>name: req.body.name,</pre><pre>email: req.body.email,</pre><pre>});<br>newUser.save().then(document =&gt; {<br>res.json({ state: true, msg: &quot;data inserted successully&quot;, document: document })</pre><pre>.catch(err =&gt; {</pre><pre>res.send(err);</pre><pre>});<br>});</pre><pre>});</pre><p>Now, send a POST request with JSON type data using Postman or any other similar application. You can see the following message if you do it correctly.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/438/1*6DD6n2GmqQcNB3RNJAGmbA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/451/1*pcEyEr_-Q3PQBX6yeZeRlA.png" /><figcaption>Output of Postman- screenshot by author</figcaption></figure><h3>Retrieve user data</h3><p>In the previous section, we have passed the data to the database, so now we have to retrieve that data. To do that You can pass a GET request with a call back function. Here method <strong>find( )<em> </em></strong>will retrieve all user’s data from the database. Then use postman and check your output as below.</p><pre>router.get(&quot;/getuser&quot;, function (req, res) {</pre><pre>User.find().then(documents =&gt; {</pre><pre>res.json({status:200,message:&#39;Users data fetched                   successfully&#39;,Userdata: documents});</pre><pre>});<br>});<br></pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/510/1*0TlRdBeS7NXhDXmm0NOTNw.png" /></figure><h3><strong>Update data</strong></h3><p>Our next CRUD operation is update user data. You can send a PUT request with user id which needs to update for this matter. And pass your data in the request body after editing them.</p><p>Actually, <strong>update( )</strong> is<strong> </strong>a deprecated feature now. Therefore <strong>updateOne( ) </strong>and <strong>updateMany( )</strong> methods are used instead of that. But <strong>updateOne()</strong> will only update one document within the collection while <strong>updateMany() </strong>will update all documents in the collection.You can choose any method among these two methods according to your requirement.</p><pre>router.put(&#39;/update/:id&#39;,(req,res,next) =&gt;{</pre><pre>const newuser = {_id:req.params.id };</pre><pre>User.updateOne(newuser,{</pre><pre>name: req.body.name,</pre><pre>email: req.body.email</pre><pre>}).then(document =&gt; {</pre><pre>if(!document){</pre><pre>return res.st(404).end();}</pre><pre>return res.status(200).json(document);</pre><pre>})</pre><pre>.catch(err =&gt; next(err));</pre><pre>)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/609/1*mTEyrzvAiqIrbKqfHmkpsQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/511/1*5FDF4od7v1OtmypuHe03nA.png" /><figcaption>Output of Postman — screenshot by the author</figcaption></figure><h3><strong>Delete data</strong></h3><p>The final crud operation is delete data from the database. As in the update method, here also we want to choose the user that needs to delete. So we pass the user id which is generated automatically by the MongoDB server.</p><pre>router.delete(&#39;/delete/:id&#39;, (req, res, next) =&gt; {</pre><pre>User.deleteOne({ _id: req.params.id }).then(document =&gt; {</pre><pre>res.json({ status: 200, message: &#39;Users data deleted Successfully&#39;, document: document });</pre><pre>})<br>.catch(err =&gt; next(err));<br>})</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/621/1*JqKu-MZYtrgN-GkY3ckf-Q.png" /><figcaption>Output of Postman — Screenshot by the author</figcaption></figure><p>These are the main CRUD operations in the database. You can also develop find user by id function as below.</p><pre>router.get(&quot;/:id&quot;, (req, res, next) =&gt; {</pre><pre>User.findById(req.params.id).then(documents =&gt; {</pre><pre>if (documents) {</pre><pre>res.status(200).json(documents);</pre><pre>} else {</pre><pre>res.status(404).json({ message: &#39;data not found&#39; });</pre><pre>}</pre><pre>});</pre><pre>});</pre><p>Your final <strong>app.js</strong> file and <strong>routeuser.js</strong> file look like this.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/36b18a5f40500fdef2e4b546649a934c/href">https://medium.com/media/36b18a5f40500fdef2e4b546649a934c/href</a></iframe><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6f8eca4715c1e09a000c33511f9d08ba/href">https://medium.com/media/6f8eca4715c1e09a000c33511f9d08ba/href</a></iframe><p>Done! You have successfully implemented database connection of your Node.js server.</p><p>Thank you for reading. Hope you learnt something. Let’s meet with another lesson in the near future.</p><p>Happy Coding!!!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e478f6efc227" width="1" height="1" alt=""><hr><p><a href="https://medium.com/swlh/connect-your-node-js-server-with-mongo-db-e478f6efc227">Connect your Node.js server with Mongo DB</a> was originally published in <a href="https://medium.com/swlh">The Startup</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Introduction to building a Nodejs server]]></title>
            <link>https://medium.com/linkit-intecs/introduction-to-building-a-nodejs-server-92ce5cba00fb?source=rss-82c5800e623------2</link>
            <guid isPermaLink="false">https://medium.com/p/92ce5cba00fb</guid>
            <category><![CDATA[development]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[expressjs]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Devindi Jayathilaka]]></dc:creator>
            <pubDate>Sat, 09 May 2020 19:09:15 GMT</pubDate>
            <atom:updated>2020-05-16T19:03:15.715Z</atom:updated>
            <content:encoded><![CDATA[<h3>Introduction to Building a Node.js Server</h3><h4>Steps to Creating a Node.js Server</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nvy_GbYi-2POut8rMmMQOA.jpeg" /><figcaption>Photo by <a href="https://www.pexels.com/@divinetechygirl">Christina Morillo</a> from <a href="https://www.pexels.com/">Pexels</a></figcaption></figure><p>Hello every one, here I will discuss how to create a server by using Node.js</p><p>First of all, you need to install Node.js to your PC and start the following developments.</p><p><a href="https://nodejs.org/en/">Node.js - Run JavaScript Everywhere</a></p><p>Create a new directory and open it using VSCode or any other development tool that you prefer. Then run npm initcommand to initialize the project. You can change default data as you like. In the end, you will have the <strong>package.json</strong> file with the data that you entered.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/625/1*mwNXDs34RhA7PAj0PRWtlg.png" /><figcaption>package.json — Screenshot By Author</figcaption></figure><p>This file is used for managing the project’s dependencies, scripts, version, etc. and it exists at the root of every Node project.</p><p>Then you need to install <strong>nodemon </strong>globally<strong>. </strong>Although it is not necessary, it automatically restarts the application. To install nodemon run,</p><p>npm install -g nodemon.</p><p>Create <strong>app.js</strong> file inside your directory. To carry on future developments you need to install <strong>express.js</strong> framework.</p><p>npm install express --save</p><p><a href="https://expressjs.com/">Express.js · Node.js web application framework</a></p><p>After the installation, import Express in your app.js file and initialize the express module in it.</p><p>const express = require(&#39;express&#39;);</p><p>const app = express();</p><p>Now you can access the express module through the app. Therefore create a server to handle server-side functionalities. Here you can choose a port number for the server to listen.</p><pre>const port = 3000<br>app.listen(port, function(){<br>  console.log(&quot;server is running port &quot; + port);<br>});</pre><p>Express.js gives us routing capabilities too. So we can give any URL pattern for a simple <strong>get </strong>request. Here I give <em>http://localhost:3000/</em>.You can give it as <em>http://localhost:3000/user</em> or any other pattern you like.</p><p>A callback function passes through the get method with two objects <strong>req</strong> and <strong>res. </strong>req object has headers of the request while the res object sends the expected data/message also known as the response.</p><pre>app.get(&quot;/&quot;,function (req, res) {<br> res.send(&quot;hello world&quot;);<br>});</pre><p>Finally, you will have following app.js file</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/11839999fdcc38b9a717968c93da847a/href">https://medium.com/media/11839999fdcc38b9a717968c93da847a/href</a></iframe><p>Now you can run the server by the command nodemon app.js In this case, you will get like this in your terminal.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/699/1*fIfsW4Y3XvWcsLNtNaTDAg.png" /><figcaption>Command Prompt — Screenshot By Author</figcaption></figure><p>You can see the output of your server here <a href="http://localhost:3000/">http://localhost:3000/</a>. Check your endpoint using a browser or postman kind of application.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/389/1*kr9ecx5yuMB5I-jt4N8ZSQ.png" /><figcaption>final Output — Screenshot By Author</figcaption></figure><p>Done! You have successfully implemented the Node.js server. Let’s meet with another lesson in the future.</p><p>Happy Coding!!!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=92ce5cba00fb" width="1" height="1" alt=""><hr><p><a href="https://medium.com/linkit-intecs/introduction-to-building-a-nodejs-server-92ce5cba00fb">Introduction to building a Nodejs server</a> was originally published in <a href="https://medium.com/linkit-intecs">LinkIT</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[OOP Concepts in Java]]></title>
            <link>https://medium.com/linkit-intecs/oop-concepts-in-java-10e895209584?source=rss-82c5800e623------2</link>
            <guid isPermaLink="false">https://medium.com/p/10e895209584</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[java8]]></category>
            <category><![CDATA[technology]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[work]]></category>
            <dc:creator><![CDATA[Devindi Jayathilaka]]></dc:creator>
            <pubDate>Wed, 02 Oct 2019 23:33:45 GMT</pubDate>
            <atom:updated>2020-05-19T18:19:12.620Z</atom:updated>
            <content:encoded><![CDATA[<h4>Understand the different characteristics of Object Oriented Programming</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*adrYRh4pDoenO2Vv" /><figcaption>Photo by <a href="https://unsplash.com/@coherent?utm_source=medium&amp;utm_medium=referral">The Coherent Team</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Hi everyone!!!</p><p>Here, Let’s learn about the different characteristics of the Object-Oriented Programming language, Java.</p><ol><li>Data Hiding</li><li>Abstraction</li><li>Encapsulation</li><li>Inheritance</li><li>Association</li><li>Polymorphism</li></ol><h3>Data Hiding</h3><p><strong><em>An outside person cannot access our internal data directly, or our internal data should not go out directly.</em></strong></p><p><strong><em>Eg:</em></strong> We are able to access our Gmail Inbox information only when we give proper authentication (username, password)</p><p><strong><em>Eg</em>:</strong> Even though we are a valid customer of a bank, only we are able to access our account information. And we can not access other’s account information.</p><p>The main advantage of data hiding is security. By declaring attributes as private we can achieve data hiding.</p><pre><em>public class Account{<br>  private double balance;<br>}</em></pre><h3>Abstraction</h3><p><strong><em>The concept of abstraction is hiding internal implementation and highlight only the set of services that we offer to the user.</em></strong></p><p>Without affecting outside implementations, we are able to modify our internal system. That means enhancements will become easy. <a href="https://www.geeksforgeeks.org/interfaces-in-java/">In Java, abstraction is achieved by interfaces and abstract classes</a>.</p><p><strong><em>Eg: </em></strong>Through a bank ATM GUI screen, the bank is highlighting the set of services that they are offering while hiding the internal implementation.</p><h3>Encapsulation</h3><p><strong><em>The process of binding data and corresponding methods into a single unit is encapsulation.</em></strong></p><p>If any component follows data hiding and abstraction, such type of a component is said to be an encapsulated component.</p><pre>public class Account{<br> <br> private double balance;</pre><pre> public double getbalance(){<br>   //validation<br>   return balance;<br> }</pre><pre> public void setBalance (int balance){<br>   this.balance = balance;<br> }<br>}</pre><p>The main advantage of encapsulation is we can achieve security, but the main disadvantage of encapsulation is it increases the length of the code and slows down the execution. If every variable in the class declared as private, that class is said to be tightly encapsulated class.</p><h3>Inheritance</h3><p><strong><em>When a child class has parent class’ properties and behaviours, then it is called inheritance.</em></strong></p><p>By using <strong>extends </strong>keyword, we can achieve inheritance in Java. This is also called as an i<strong>s-a relationship</strong>.</p><pre>class Parent{<br>  public void m1() {<br>    System.out.println(&quot;parent&quot;);<br>  }<br>}</pre><pre>class Child extends Parent{<br>  public void m2(){<br>    System.out.println(&quot;child&quot;);<br>  }<br>}</pre><pre>class Test{<br>  public static void main(String[] args) {<br>   Child c = new Child();<br>   c.m1();<br>   c.m2();<br>  }<br>}</pre><h4>Why We Need Inheritance?</h4><p>When two or more similar classes have common methods and behaviours, we can use inheritance. After creating the child class, the common methods and behaviours inherited to child class as well. <a href="https://www.educba.com/what-is-inheritance-in-programming/">Therefore by avoiding duplicity, data redundancy is decreased by using inheritance.</a></p><h4>Why Java Does Not Support Multiple Inheritance?</h4><p>A Java class cannot extend more than one class at a time. Hence Java does not support multiple inheritances in classes.</p><p>But, this is achievable by implementing multiple interfaces.</p><h3>Association</h3><p><strong><em>Association (has-a relationship) is the relationship between objects. It can be a form of composition or aggregation. The main advantage of a has-a relationship is the reusability of the code.</em></strong></p><p>The<strong> composition</strong> represents the relationship where one object contains other objects as a part of its state. There is a strong relationship between the containing object and the dependent object.</p><p><strong><em>Eg: </em></strong><em>U</em>niversity and departments are strongly associated. Without a university, there is no chance for departments to exist.</p><p>In <strong>Aggregation</strong>, there is a week relationship between the containing object and the dependent object.</p><p><strong><em>Eg: </em></strong>Department consists of several professors. Even without the department exists, there may be a chance for professors to exist. Hence department and professor objects are weekly associated.</p><h3>Polymorphism</h3><p><strong><em>Polymorphism is when an object can be defined in many forms.</em></strong></p><p>It can be divided into <strong>compile-time polymorphism (overloading)</strong> and <strong>run-time polymorphism (overriding).</strong></p><p>If child class is not satisfied with parent class implementation then the child is allowed to redefine the method based on the child’s requirement. This process is called overriding.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0d3f51e5dbdb4bdd7eccede434b531cb/href">https://medium.com/media/0d3f51e5dbdb4bdd7eccede434b531cb/href</a></iframe><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2cfa3776a4abe73720eef1e28895cafd/href">https://medium.com/media/2cfa3776a4abe73720eef1e28895cafd/href</a></iframe><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f95b26d2738bfedc6e64f025b823e158/href">https://medium.com/media/f95b26d2738bfedc6e64f025b823e158/href</a></iframe><p>Here method <em>draw</em> is overridden in the child classes. And an actual implementation of the interface Shape will be used at runtime, hence overriding is called as runtime polymorphism.</p><p>If a class has the same method name with different parameters, such type is called method overloading. Here compiler will be able to identify the method to invoke at compile-time.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8ebe6310ee972b142817ad9b0d99fc4a/href">https://medium.com/media/8ebe6310ee972b142817ad9b0d99fc4a/href</a></iframe><p>Thank you for reading. Hope you learnt something. Let’s meet with another lesson in the near future.</p><p>Happy Coding!!!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=10e895209584" width="1" height="1" alt=""><hr><p><a href="https://medium.com/linkit-intecs/oop-concepts-in-java-10e895209584">OOP Concepts in Java</a> was originally published in <a href="https://medium.com/linkit-intecs">LinkIT</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to connect spring application with MySql Database]]></title>
            <link>https://medium.com/linkit-intecs/how-to-connect-spring-application-with-mysql-database-55821314ba5?source=rss-82c5800e623------2</link>
            <guid isPermaLink="false">https://medium.com/p/55821314ba5</guid>
            <category><![CDATA[java]]></category>
            <category><![CDATA[spring-boot]]></category>
            <category><![CDATA[database]]></category>
            <category><![CDATA[development]]></category>
            <category><![CDATA[mysql]]></category>
            <dc:creator><![CDATA[Devindi Jayathilaka]]></dc:creator>
            <pubDate>Mon, 12 Aug 2019 14:38:10 GMT</pubDate>
            <atom:updated>2021-09-11T08:15:25.766Z</atom:updated>
            <content:encoded><![CDATA[<h3>Connect your Spring Boot Server with MySQL Database</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*1dL5AdMqjmbMCat1" /><figcaption>Photo by <a href="https://unsplash.com/@tfrants?utm_source=medium&amp;utm_medium=referral">Tyler Franta</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Hi everyone!!!</p><p>Let’s discuss how to implement main services as Add a user, Retrieve user data, update the user, find a user by id, and delete a user that generally calls main <strong>CRUD</strong> operations.</p><p>Create a new Maven project which is consists of web, JPA, and MySQL dependencies. Inside the project create the following packages</p><ol><li>Controllers</li><li>Domain</li><li>Repositories</li><li>Services</li></ol><p>Then create a Java class called <strong>User</strong> inside the controller&#39;s package. Call the API endpoints by using Rest Controller &amp; Request mapping annotations. Create methods that are called the rest services. To do that create the following API endpoints,</p><ul><li>To get all user data inside the database create @GetMapping(“/all”)</li><li>To add new user create @PostMapping(“/add”)</li><li>To update user data @PutMapping(“/update”)</li><li>To find a user by id @GetMapping(“/find/{id}”)</li><li>To delete user @DeleteMapping(“/delete”)</li></ul><p>Note that user data will retrieve as a list. Therefore its return type is</p><p>List&lt; UserDTO&gt;</p><p>Note that when you are going to add a new user, pass the user data as a list inside the body. Therefore @RequestBody annotation is used here.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9f5f104e73a05d3ea6711056e622ed86/href">https://medium.com/media/9f5f104e73a05d3ea6711056e622ed86/href</a></iframe><p>Then Create the user entity inside the Domain package. To do that you need to create <strong>UserDTO.java </strong>class and set the getters and setters for each attribute. Use the user id as an auto-generated value.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/16b2028b95be57080159bd76c573f4c3/href">https://medium.com/media/16b2028b95be57080159bd76c573f4c3/href</a></iframe><p>To use <strong>JPA (Java Persistence API)</strong> create an interface called User Repository under the Repository package. Then extends it from JPA Repositories. Here JPA repository requests the name of the data layer and the data type of the primary key.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1769ffe7fc5f6b674eaa990bf27b524f/href">https://medium.com/media/1769ffe7fc5f6b674eaa990bf27b524f/href</a></iframe><p>JPA repository is also an interface that consists of several methods. You can learn more about JPA by the following website.</p><p><a href="https://www.javaworld.com/article/3379043/what-is-jpa-introduction-to-the-java-persistence-api.html">What is JPA? Introduction to the Java Persistence API</a></p><p>Ok, let’s move on…</p><p>Inside the service, the package creates user services and their implementation. Inside the service implementation class use the user repository as dependency injection. Now you can call the methods which are in the user repository that extends from the JPA repository. Put @Autowired annotation to show dependency injection.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7323514f009e43590d1c93af3e5081fc/href">https://medium.com/media/7323514f009e43590d1c93af3e5081fc/href</a></iframe><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f00bdc4644ab5aeaa81ae2ff2e5e1ecd/href">https://medium.com/media/f00bdc4644ab5aeaa81ae2ff2e5e1ecd/href</a></iframe><h4>Create your Database connection</h4><p><a href="https://spring.io/guides/gs/accessing-data-mysql/">Getting Started | Accessing data with MySQL</a></p><p>To connect the database you must define the connection attributes in the application.properties file which is already in the resources package.</p><pre>spring.jpa.hibernate.ddl-auto=update<br>spring.datasource.url=jdbc:mysql://localhost:3306/spring<br>spring.datasource.username=root<br>spring.datasource.password=<br>spring.jpa.show-sql=<strong>true</strong></pre><p>Give a name to your database and set a username and password if you have. Give show-SQL as true to show the changes of SQL query in the console after running the application.</p><p>Now all the requirements are over. To create the database run this application. Then check whether your database using PHPMyAdmin.Now you should pass the data to the database by using post request. To do that open the Postman or any other similar application and call the endpoints.</p><p>Note that you should pass the data as a JSON type. ( JSON stands for <strong>J</strong>ava<strong>S</strong>cript <strong>O</strong>bject <strong>N</strong>otation). For more details follow.</p><p><a href="https://www.w3schools.com/whatis/whatis_json.asp">What is JSON</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CLqGm1csaxThJWQZdYSWoQ.png" /><figcaption>The output of Postman — screenshot by the author</figcaption></figure><p>You can see the “data saved” message if it is successfully done. In this way, you can send</p><ol><li><a href="http://localhost:8080/user/add">http://localhost:8080/user/add</a> <strong>GET</strong> request to retrieve data,</li></ol><p>2. <a href="http://localhost:8080/user/update">http://localhost:8080/user/update</a> <strong>PUT</strong> request to update data,</p><p>3. <a href="http://localhost:8080/user/find/%7Bid%7D">http://localhost:8080/user/find/{id}</a><strong> Get</strong> request to find a user,</p><p>4. http://localhost:8080/user/delete <strong>DELETE</strong> request with relevant data set to delete a user from the database.</p><p>In this way, you can develop main CRUD operations by using Spring Boot. To get the full code of this project visit,</p><p><a href="https://github.com/devindianushika/spring-crud">devindianushika/spring-crud</a></p><p>Thank you for reading. Let’s meet with another article in the near future.</p><p>Happy coding!!!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=55821314ba5" width="1" height="1" alt=""><hr><p><a href="https://medium.com/linkit-intecs/how-to-connect-spring-application-with-mysql-database-55821314ba5">How to connect spring application with MySql Database</a> was originally published in <a href="https://medium.com/linkit-intecs">LinkIT</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[What’s first in spring boot with intellij IDEA]]></title>
            <link>https://devindijayathilaka.medium.com/what-first-in-spring-boot-with-intellij-idea-81c829da35db?source=rss-82c5800e623------2</link>
            <guid isPermaLink="false">https://medium.com/p/81c829da35db</guid>
            <category><![CDATA[java]]></category>
            <dc:creator><![CDATA[Devindi Jayathilaka]]></dc:creator>
            <pubDate>Mon, 17 Jun 2019 19:36:49 GMT</pubDate>
            <atom:updated>2020-05-17T16:20:18.782Z</atom:updated>
            <content:encoded><![CDATA[<h3>What’s First In Spring Boot With IntelliJ IDEA</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*fEggS6bk8fsqVUnV" /><figcaption>Photo by <a href="https://unsplash.com/@alexacea?utm_source=medium&amp;utm_medium=referral">Alexandru Acea</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3>What is spring?</h3><p>A web framework to built Enterprise Applications by using Java.Because of the large configurations it is recommended to bootsrap the spring framework.</p><p><a href="https://spring.io/">Home</a></p><p>Let’s build our first springboot programme</p><p>Make sure your pc has installed jdk 8.By using intellij IDEA,create a new Maven project</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1017/1*vJX4n_GskOL82POiicf6dQ.png" /></figure><p>By clicking “Next” you will receive following</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jX11lxE_kpjl0FnuurLCbg.png" /></figure><p>Group id should be your company/Group name,Artifact id is your project name</p><p>Then enter the dependencies that you want to built up the project.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8zXT1vDnXwdx4wsxLCUx2g.png" /></figure><p>After finishing the process create the directory structure,</p><p><strong>src&gt;&gt;&gt; main&gt;&gt;&gt; java&gt;&gt;&gt;SpringDemoApplication</strong></p><p>To identify API end points create controller package,under controller package create a java class <strong>“First”</strong></p><p>Using Annotation @Restcontroller define the class is Rest API accept one and the annotation @Requestmapping maps HTTP requests to handler methods of MVC and REST controllers.Put the relevant url name.</p><p>To map HTTP GET request onto specific handler method use @GetMapping .Inside the class create the method.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/89f3ec4022b5474d89a8e3dcbdb97b6f/href">https://medium.com/media/89f3ec4022b5474d89a8e3dcbdb97b6f/href</a></iframe><p>After running the programme we can check the output as follow</p><p><a href="http://localhost:8080/end/hello">https://localhost:8080/end/hello</a></p><p>Done!. You have successfully implemented first springboot programme</p><p>To get full code of this project visit</p><p><a href="https://github.com/devindianushika/SpringbootFirst">devindianushika/SpringbootFirst</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=81c829da35db" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>