<?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"><channel><title><![CDATA[Amr's Tech Universe]]></title><description><![CDATA[Amr's Tech Universe]]></description><link>https://amrtechuniverse.com</link><image><url>https://cdn.hashnode.com/res/hashnode/image/upload/v1646471924162/QQHNYmPOQ.png</url><title>Amr&apos;s Tech Universe</title><link>https://amrtechuniverse.com</link></image><generator>RSS for Node</generator><lastBuildDate>Sat, 11 Apr 2026 11:57:52 GMT</lastBuildDate><atom:link href="https://amrtechuniverse.com/rss.xml" rel="self" type="application/rss+xml"/><language><![CDATA[en]]></language><ttl>60</ttl><item><title><![CDATA[Docker: A Beginner's guide]]></title><description><![CDATA[Docker: Use Cases and Why Docker is Important
Introduction
Docker has become an essential tool for modern software development and deployment. It enables developers to package their applications and dependencies into portable containers, making it ea...]]></description><link>https://amrtechuniverse.com/docker-a-beginners-guide</link><guid isPermaLink="true">https://amrtechuniverse.com/docker-a-beginners-guide</guid><category><![CDATA[Docker]]></category><category><![CDATA[Docker compose]]></category><category><![CDATA[Dockerfile]]></category><category><![CDATA[Devops]]></category><dc:creator><![CDATA[Amr Khaled]]></dc:creator><pubDate>Sat, 22 Apr 2023 16:48:50 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1682182122987/672bfe37-3890-4408-96cd-4fd2c3ceafae.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>Docker: Use Cases and Why Docker is Important</p>
<h2 id="heading-introduction"><strong>Introduction</strong></h2>
<p>Docker has become an essential tool for modern software development and deployment. It enables developers to package their applications and dependencies into portable containers, making it easier to build, ship, and run applications across different environments. Docker also provides several benefits, including consistency, portability, scalability, and isolation. In this article, we will explore Docker and Docker Compose and their use cases, as well as discuss why Docker is important.</p>
<h2 id="heading-docker"><strong>Docker</strong></h2>
<p>Docker is a platform for building, shipping, and running applications in containers. A container is a lightweight and standalone executable package that contains all the necessary software components, including the application code, dependencies, libraries, and runtime. Containers are isolated from each other and from the host system, which makes them secure and portable. Docker provides several benefits, including:</p>
<ul>
<li><p>Consistency: Docker ensures that the application runs the same way on any environment, whether it's a developer's machine or a production server.</p>
</li>
<li><p>Portability: Docker containers can be moved between different environments, including development, testing, staging, and production, without any changes to the application code.</p>
</li>
<li><p>Scalability: Docker enables developers to scale their applications horizontally by adding more containers to handle increased traffic or load.</p>
</li>
<li><p>Isolation: Docker containers are isolated from each other and from the host system, which makes them secure and reliable.</p>
</li>
</ul>
<h2 id="heading-docker-compose"><strong>Docker Compose</strong></h2>
<p>Docker Compose is a tool for defining and running multi-container Docker applications. It enables developers to define the services, networks, and volumes required by their applications in a YAML file, which can be versioned and shared with the team. Docker Compose also provides several benefits, including:</p>
<ul>
<li><p>Simplicity: Docker Compose simplifies the deployment of multi-container applications by defining the dependencies and relationships between the services.</p>
</li>
<li><p>Modularity: Docker Compose enables developers to break down their applications into smaller, modular components, which can be tested and deployed independently.</p>
</li>
<li><p>Reproducibility: Docker Compose ensures that the same set of services and dependencies are used across different environments, making it easier to reproduce issues and debug them.</p>
</li>
</ul>
<h2 id="heading-use-cases"><strong>Use Cases</strong></h2>
<p>Docker and Docker Compose can be used in a variety of scenarios, including:</p>
<ul>
<li><p>Development: Docker enables developers to create a consistent and isolated development environment, which can be shared with the team. Docker Compose enables developers to define the services required by their applications, such as a database, cache, or message queue, and run them locally.</p>
</li>
<li><p>Testing: Docker enables developers to create a consistent and isolated testing environment, which can be used to run automated tests. Docker Compose enables developers to define the services required by the tests and run them in a containerized environment.</p>
</li>
<li><p>Staging: Docker enables developers to create a consistent and isolated staging environment, which can be used to test the application before it's deployed to production. Docker Compose enables developers to define the services required by the staging environment and run them in a containerized environment.</p>
</li>
<li><p>Production: Docker enables developers to deploy their applications in a consistent and portable way, making it easier to scale and manage them. Docker Compose enables developers to define the services required by the application in production and manage them using an orchestration tool, such as Docker Swarm or Kubernetes.</p>
</li>
</ul>
<h2 id="heading-volumes"><strong>Volumes</strong></h2>
<p>Volumes are a way to persist data between Docker container runs. They are used to store data that needs to survive container restarts or to share data between containers. Volumes can be created and managed using Docker commands or Docker Compose. For example, the following Docker Compose file defines a volume for a database container:</p>
<pre><code class="lang-yaml"><span class="hljs-attr">version:</span> <span class="hljs-string">'3'</span>

<span class="hljs-attr">services:</span>
  <span class="hljs-attr">db:</span>
    <span class="hljs-attr">image:</span> <span class="hljs-string">mysql</span>
    <span class="hljs-attr">volumes:</span>
      <span class="hljs-bullet">-</span> <span class="hljs-string">db-data:/var/lib/mysql</span>

<span class="hljs-attr">volumes:</span>
  <span class="hljs-attr">db-data:</span>
</code></pre>
<p>In this example, a volume named <code>db-data</code> is defined, and the <code>db</code> service uses it to persist the database data.</p>
<h2 id="heading-networks"><strong>Networks</strong></h2>
<p>Docker provides several types of networks for container communication, including bridge, host, overlay, and macvlan networks. Bridge networks are the default type and are used to connect containers running on the same Docker host. Host networks allow containers to share the host network namespace, while overlay networks are used for container communication across multiple Docker hosts. Macvlan networks enable containers to have their own MAC address and be treated like physical machines on the network.</p>
<p>Docker Compose enables developers to define networks and connect services to them. For example, the following Docker Compose file defines a bridge network and connects two services to it:</p>
<pre><code class="lang-yaml"><span class="hljs-attr">version:</span> <span class="hljs-string">'3'</span>

<span class="hljs-attr">services:</span>
  <span class="hljs-attr">web:</span>
    <span class="hljs-attr">image:</span> <span class="hljs-string">nginx</span>
    <span class="hljs-attr">networks:</span>
      <span class="hljs-bullet">-</span> <span class="hljs-string">webnet</span>
  <span class="hljs-attr">db:</span>
    <span class="hljs-attr">image:</span> <span class="hljs-string">mysql</span>
    <span class="hljs-attr">networks:</span>
      <span class="hljs-bullet">-</span> <span class="hljs-string">webnet</span>

<span class="hljs-attr">networks:</span>
  <span class="hljs-attr">webnet:</span>
</code></pre>
<p>In this example, a bridge network named <code>webnet</code> is defined, and the <code>web</code> and <code>db</code> services are connected to it.</p>
<p>Docker networks allow containers to communicate with each other and with the outside world. By default, containers in the same network can communicate with each other using their container names as hostnames. However, it's also possible to configure Docker networks to provide more granular control over network access.</p>
<p>In a Docker Compose file with multiple modules, it's common to create multiple networks to segregate network access for different projects. For example, you might have a backend that uses a network named "public" to expose APIs to the outside world, and another network named "private" for internal communication with a database. You might also have a frontend module that only needs access to the "public" network.</p>
<p>Here's an example Docker Compose file that sets up multiple networks:</p>
<pre><code class="lang-yaml"><span class="hljs-attr">version:</span> <span class="hljs-string">'3'</span>

<span class="hljs-attr">services:</span>
  <span class="hljs-attr">backend:</span>
    <span class="hljs-attr">build:</span> <span class="hljs-string">.</span>
    <span class="hljs-attr">networks:</span>
      <span class="hljs-bullet">-</span> <span class="hljs-string">public</span>
      <span class="hljs-bullet">-</span> <span class="hljs-string">private</span>
    <span class="hljs-attr">depends_on:</span>
      <span class="hljs-bullet">-</span> <span class="hljs-string">db</span>

  <span class="hljs-attr">db:</span>
    <span class="hljs-attr">image:</span> <span class="hljs-string">postgres</span>
    <span class="hljs-attr">networks:</span>
      <span class="hljs-bullet">-</span> <span class="hljs-string">private</span>

  <span class="hljs-attr">frontend:</span>
    <span class="hljs-attr">build:</span> <span class="hljs-string">.</span>
    <span class="hljs-attr">networks:</span>
      <span class="hljs-bullet">-</span> <span class="hljs-string">public</span>

<span class="hljs-attr">networks:</span>
  <span class="hljs-attr">public:</span>
  <span class="hljs-attr">private:</span>
</code></pre>
<p>In this example, there are three services defined: <code>backend</code>, <code>db</code>, and <code>frontend</code>. The <code>backend</code> and <code>frontend</code> services both use the <code>public</code> network, while the <code>backend</code> and <code>db</code> services both use the <code>private</code> network.</p>
<p>The <code>networks</code> section defines the two networks used by the services. By default, Docker creates a bridge network for each Compose file, but additional networks can be defined using the <code>networks</code> section.</p>
<p>To access a service on a different network, you can specify the network name when referencing the service in your code. For example, if the <code>backend</code> service needs to communicate with the <code>db</code> service, it can use the hostname <code>db</code> and the network name <code>private</code>, like this:</p>
<pre><code class="lang-bash">postgres://db:5432/mydatabase
</code></pre>
<p>By using multiple networks in your Docker Compose file, you can provide more granular control over network access and better isolate your services.</p>
<h2 id="heading-services"><strong>Services</strong></h2>
<p>Services are the building blocks of Docker Compose applications. They represent the containers that make up the application and can be defined with various configuration options, including the image, command, environment variables, ports, volumes, and networks.</p>
<p>For example, the following Docker Compose file defines two services, a web server and a database:</p>
<pre><code class="lang-yaml"><span class="hljs-attr">version:</span> <span class="hljs-string">'3'</span>

<span class="hljs-attr">services:</span>
  <span class="hljs-attr">web:</span>
    <span class="hljs-attr">image:</span> <span class="hljs-string">nginx</span>
    <span class="hljs-attr">ports:</span>
      <span class="hljs-bullet">-</span> <span class="hljs-string">"80:80"</span>
  <span class="hljs-attr">db:</span>
    <span class="hljs-attr">image:</span> <span class="hljs-string">mysql</span>
    <span class="hljs-attr">environment:</span>
      <span class="hljs-attr">MYSQL_ROOT_PASSWORD:</span> <span class="hljs-string">password</span>
</code></pre>
<p>In this example, the <code>web</code> service uses the <code>nginx</code> image and maps port 80 on the host to port 80 in the container. The <code>db</code> service uses the <code>mysql</code> image and sets the <code>MYSQL_ROOT_PASSWORD</code> environment variable.</p>
<h2 id="heading-dockerfile-and-docker-composeyaml-structure"><strong>Dockerfile and docker-compose.yaml Structure</strong></h2>
<p>A Dockerfile is a text file that contains instructions for building a Docker image. Each instruction in the Dockerfile creates a new layer in the image, and the final image is the result of executing all the instructions in order. A typical Dockerfile contains the following sections:</p>
<ul>
<li><p><strong>FROM</strong>: specifies the base image for the Docker image.</p>
</li>
<li><p><strong>ENV</strong>: sets environment variables in the container.</p>
</li>
<li><p><strong>RUN</strong>: runs a command inside the container to install packages or configure the environment.</p>
</li>
<li><p><strong>COPY/ADD</strong>: copies files from the host machine to the container.</p>
</li>
<li><p><strong>CMD/ENTRYPOINT</strong>: specifies the command to run when the container starts.</p>
</li>
</ul>
<p>Here is an example Dockerfile for a Node.js application:</p>
<pre><code class="lang-yaml"><span class="hljs-string">FROM</span> <span class="hljs-string">node:12</span>

<span class="hljs-string">WORKDIR</span> <span class="hljs-string">/app</span>

<span class="hljs-string">COPY</span> <span class="hljs-string">package*.json</span> <span class="hljs-string">./</span>

<span class="hljs-string">RUN</span> <span class="hljs-string">npm</span> <span class="hljs-string">install</span>

<span class="hljs-string">COPY</span> <span class="hljs-string">.</span> <span class="hljs-string">.</span>

<span class="hljs-string">EXPOSE</span> <span class="hljs-number">3000</span>

<span class="hljs-string">CMD</span> [ <span class="hljs-string">"npm"</span>, <span class="hljs-string">"start"</span> ]
</code></pre>
<p>In this example, we start with the <code>node:12</code> base image, set the working directory to <code>/app</code>, copy the <code>package*.json</code> files to the container, run <code>npm install</code> to install dependencies, copy the rest of the application code, expose port 3000, and set the <code>npm start</code> command to run when the container starts.</p>
<p>A <code>docker-compose.yaml</code> file defines a multi-container application, including the services that make up the application, the Dockerfiles used to build the services, and the networks and volumes used by the services. A typical <code>docker-compose.yaml</code> file contains the following sections:</p>
<ul>
<li><p><strong>version</strong>: specifies the Docker Compose version.</p>
</li>
<li><p><strong>services</strong>: defines the services that make up the application.</p>
</li>
<li><p><strong>build</strong>: specifies the Dockerfile to use to build each service.</p>
</li>
<li><p><strong>volumes</strong>: defines the volumes used by the services.</p>
</li>
<li><p><strong>networks</strong>: defines the networks used by the services.</p>
</li>
</ul>
<p>Here is an example <code>docker-compose.yaml</code> file for a Node.js application with a web server and a database:</p>
<pre><code class="lang-yaml"><span class="hljs-attr">version:</span> <span class="hljs-string">'3'</span>

<span class="hljs-attr">services:</span>
  <span class="hljs-attr">web:</span>
    <span class="hljs-attr">build:</span> <span class="hljs-string">.</span>
    <span class="hljs-attr">ports:</span>
      <span class="hljs-bullet">-</span> <span class="hljs-string">"3000:3000"</span>
    <span class="hljs-attr">volumes:</span>
      <span class="hljs-bullet">-</span> <span class="hljs-string">.:/app</span>
    <span class="hljs-attr">depends_on:</span>
      <span class="hljs-bullet">-</span> <span class="hljs-string">db</span>
  <span class="hljs-attr">db:</span>
    <span class="hljs-attr">image:</span> <span class="hljs-string">mysql</span>
    <span class="hljs-attr">environment:</span>
      <span class="hljs-attr">MYSQL_ROOT_PASSWORD:</span> <span class="hljs-string">password</span>
</code></pre>
<p>In this example, we define two services, <code>web</code> and <code>db</code>. The <code>web</code> service uses the Dockerfile in the current directory to build the image, maps port 3000 on the host to port 3000 in the container, mounts the current directory as a volume in the container, and depends on the <code>db</code> service. The <code>db</code> service uses the <code>mysql</code> image and sets the <code>MYSQL_ROOT_PASSWORD</code> environment variable.</p>
<h2 id="heading-dockerfile-best-practices"><strong>DockerFile Best Practices</strong></h2>
<p>Dockerfile is a simple text file that contains instructions for building a Docker image, It is an essential component of the Docker ecosystem, and it plays a critical role in creating high-quality images that are easy to manage and deploy. Here are some best practices for writing Dockerfiles:</p>
<ol>
<li><p><strong>Use a Minimal Base Image</strong>: When creating Docker images, it's best to start with a minimal base image. This reduces the size of the image and makes it more efficient to manage. A minimal base image should only include the necessary components required to run your application.</p>
</li>
<li><p><strong>Use Layer Caching</strong>: Docker images are built using layers. Each instruction in a Dockerfile creates a new layer. When building images, Docker caches layers that have not changed since the last build. By using layer caching, you can speed up the build process and reduce the amount of data that needs to be transferred.</p>
</li>
<li><p><strong>Clean Up After Each Step</strong>: When creating a Docker image, it's important to remove any files or directories that are no longer needed after each step. This ensures that the image is as small as possible and reduces the risk of security vulnerabilities.</p>
</li>
<li><p><strong>Run Containers as Non-Root Users</strong>: By default, Docker containers run as the root user. However, this can be a security risk. It's best to run containers as non-root users whenever possible.</p>
</li>
<li><p><strong>Use .dockerignore</strong>: When building a Docker image, it's important to only include the necessary files and directories. Using .dockerignore can help to exclude unnecessary files and directories from the build context. This reduces the size of the build context and speeds up the build process.</p>
</li>
<li><p><strong>Use ENV Instead of ARG</strong>: When defining environment variables in a Dockerfile, it's best to use ENV instead of ARG. ENV sets an environment variable that persists in the container, while ARG is only available during the build process.</p>
</li>
<li><p><strong>Use LABEL</strong>: Docker labels can be used to add metadata to an image. This can be useful for tracking image versions, maintaining an audit trail, and providing additional information about the image.</p>
</li>
<li><p><strong>Use HEALTHCHECK</strong>: Docker HEALTHCHECK can be used to check the health of a container. This can be useful for detecting and addressing issues before they become critical.</p>
</li>
<li><p><strong>Use COPY Instead of ADD</strong>: When copying files to a Docker image, it's best to use COPY instead of ADD. COPY only copies the specified files, while ADD can also unpack compressed files, which can be a security risk.</p>
</li>
</ol>
<p>By following these best practices, you can create high-quality Docker images that are efficient, secure, and easy to manage.</p>
<h2 id="heading-pushing-docker-images-to-a-private-repository"><strong>Pushing Docker Images to a Private Repository</strong></h2>
<p>Docker images can be pushed to a private repository, such as Docker Hub or AWS ECR, for sharing with the team or deployment to production. The following steps demonstrate how to push a Docker image to a private repository and tag and version it:</p>
<ol>
<li><p>Build the Docker image: <code>docker build -t my-image:v1 .</code></p>
</li>
<li><p>Tag the Docker image with the private repository: `docker tag my-image:v1 my-repo/my-image</p>
</li>
</ol>
<ol>
<li><p>Login to the private repository: <code>docker login my-repo</code></p>
</li>
<li><p>Push the Docker image to the private repository: <code>docker push my-repo/my-image:v1</code></p>
</li>
</ol>
<h2 id="heading-conclusion">Conclusion</h2>
<p>In conclusion, Docker has become an essential tool for modern software development and deployment. Its benefits include consistency, portability, scalability, and isolation. With Docker, developers can package their applications and dependencies into portable containers, making it easier to build, ship, and run applications across different environments. Docker Compose simplifies the deployment of multi-container applications by defining the dependencies and relationships between the services, enabling developers to break down their applications into smaller, modular components that can be tested and deployed independently. Docker and Docker Compose can be used in a variety of scenarios, from development and testing to staging and production. Volumes and networks are also important concepts in Docker, allowing developers to persist data between Docker container runs and to connect containers to different types of networks.</p>
]]></content:encoded></item><item><title><![CDATA[Using Spring Boot with Apache Kafka: Building Event-Driven Systems]]></title><description><![CDATA[Using Spring Boot with Apache Kafka: Building Event-Driven Systems
Event-driven architectures are becoming increasingly popular as organizations move towards more distributed and decoupled systems. Apache Kafka is a popular open-source distributed st...]]></description><link>https://amrtechuniverse.com/using-spring-boot-with-apache-kafka-building-event-driven-systems</link><guid isPermaLink="true">https://amrtechuniverse.com/using-spring-boot-with-apache-kafka-building-event-driven-systems</guid><category><![CDATA[Springboot]]></category><category><![CDATA[Spring]]></category><category><![CDATA[kafka]]></category><category><![CDATA[messaging]]></category><dc:creator><![CDATA[Amr Khaled]]></dc:creator><pubDate>Sat, 25 Feb 2023 14:30:39 GMT</pubDate><content:encoded><![CDATA[<h1 id="heading-using-spring-boot-with-apache-kafka-building-event-driven-systems"><strong>Using Spring Boot with Apache Kafka: Building Event-Driven Systems</strong></h1>
<p>Event-driven architectures are becoming increasingly popular as organizations move towards more distributed and decoupled systems. Apache Kafka is a popular open-source distributed streaming platform that can be used to build event-driven systems. In this article, we will explore how to use Spring Boot with Apache Kafka to build event-driven systems.</p>
<h2 id="heading-what-is-apache-kafka"><strong>What is Apache Kafka?</strong></h2>
<p>Apache Kafka is a distributed streaming platform that is used to build real-time data pipelines and streaming applications. It provides a unified, high-throughput, low-latency platform for handling real-time data feeds. Kafka can be used for a wide range of use cases, including:</p>
<ul>
<li><p>Log aggregation</p>
</li>
<li><p>Stream processing</p>
</li>
<li><p>Event sourcing</p>
</li>
<li><p>Messaging</p>
</li>
</ul>
<p>Kafka is a distributed system, which means it is designed to run across multiple servers, known as brokers. Each broker stores a subset of the data, and data is replicated across multiple brokers for fault tolerance.</p>
<h2 id="heading-setting-up-a-kafka-cluster"><strong>Setting up a Kafka Cluster</strong></h2>
<p>Before we dive into using Kafka with Spring Boot, we need to set up a Kafka cluster. A Kafka cluster typically consists of one or more Kafka brokers, which are responsible for storing and managing data, and one or more ZooKeeper servers, which are used for coordination and configuration.</p>
<h3 id="heading-setting-up-a-kafka-cluster-with-docker"><strong>Setting up a Kafka Cluster with Docker</strong></h3>
<p>We can set up a Kafka cluster locally using Docker by running the following commands:</p>
<pre><code class="lang-bash">docker-compose up -d zookeeper
docker-compose up -d kafka
</code></pre>
<p>This will create a Kafka cluster with one ZooKeeper server and one Kafka broker.</p>
<h3 id="heading-setting-up-a-kafka-cluster-without-docker"><strong>Setting up a Kafka Cluster without Docker</strong></h3>
<p>To set up a Kafka cluster without Docker, we need to follow the following steps:</p>
<ol>
<li><p>Download and install Kafka from the <a target="_blank" href="https://kafka.apache.org/downloads"><strong>official website</strong></a>.</p>
</li>
<li><p>Start a ZooKeeper server:</p>
<pre><code class="lang-bash"> bin/zookeeper-server-start.sh config/zookeeper.properties
</code></pre>
</li>
<li><p>Start one or more Kafka brokers:</p>
<pre><code class="lang-bash"> bin/kafka-server-start.sh config/server.properties
</code></pre>
<p> By default, Kafka uses port 9092 for communication between brokers and clients.</p>
</li>
</ol>
<h2 id="heading-creating-a-spring-boot-kafka-application"><strong>Creating a Spring Boot Kafka Application</strong></h2>
<p>To create a Spring Boot Kafka application, we need to add the following dependencies to our <code>pom.xml</code> file:</p>
<pre><code class="lang-xml"><span class="hljs-tag">&lt;<span class="hljs-name">dependency</span>&gt;</span>
  <span class="hljs-tag">&lt;<span class="hljs-name">groupId</span>&gt;</span>org.springframework.kafka<span class="hljs-tag">&lt;/<span class="hljs-name">groupId</span>&gt;</span>
  <span class="hljs-tag">&lt;<span class="hljs-name">artifactId</span>&gt;</span>spring-kafka<span class="hljs-tag">&lt;/<span class="hljs-name">artifactId</span>&gt;</span>
  <span class="hljs-tag">&lt;<span class="hljs-name">version</span>&gt;</span>2.7.3<span class="hljs-tag">&lt;/<span class="hljs-name">version</span>&gt;</span>
<span class="hljs-tag">&lt;/<span class="hljs-name">dependency</span>&gt;</span>
<span class="hljs-tag">&lt;<span class="hljs-name">dependency</span>&gt;</span>
  <span class="hljs-tag">&lt;<span class="hljs-name">groupId</span>&gt;</span>org.springframework.boot<span class="hljs-tag">&lt;/<span class="hljs-name">groupId</span>&gt;</span>
  <span class="hljs-tag">&lt;<span class="hljs-name">artifactId</span>&gt;</span>spring-boot-starter-web<span class="hljs-tag">&lt;/<span class="hljs-name">artifactId</span>&gt;</span>
  <span class="hljs-tag">&lt;<span class="hljs-name">version</span>&gt;</span>2.7.6<span class="hljs-tag">&lt;/<span class="hljs-name">version</span>&gt;</span>
<span class="hljs-tag">&lt;/<span class="hljs-name">dependency</span>&gt;</span>
</code></pre>
<p>We can then create a simple Kafka producer that sends a message to a Kafka topic:</p>
<pre><code class="lang-java"><span class="hljs-meta">@RestController</span>
<span class="hljs-meta">@RequestMapping("/kafka")</span>
<span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">KafkaProducerController</span> </span>{
    <span class="hljs-keyword">private</span> <span class="hljs-keyword">final</span> KafkaTemplate&lt;String, String&gt; kafkaTemplate;
    <span class="hljs-keyword">private</span> <span class="hljs-keyword">final</span> String topicName = <span class="hljs-string">"test-topic"</span>;

    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-title">KafkaProducerController</span><span class="hljs-params">(KafkaTemplate&lt;String, String&gt; kafkaTemplate)</span> </span>{
        <span class="hljs-keyword">this</span>.kafkaTemplate = kafkaTemplate;
    }

    <span class="hljs-meta">@PostMapping("/publish")</span>
    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">sendMessage</span><span class="hljs-params">(<span class="hljs-meta">@RequestBody</span> String message)</span> </span>{
        kafkaTemplate.send(topicName, message);
    }
}
</code></pre>
<p>We can also create a Kafka consumer that listens to the same Kafka topic:</p>
<pre><code class="lang-java"><span class="hljs-meta">@Service</span>
<span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">KafkaConsumer</span> </span>{
    <span class="hljs-meta">@KafkaListener(topics = "test-topic", groupId = "group_id")</span>
    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">consume</span><span class="hljs-params">(String message)</span> </span>{
        System.out.println(<span class="hljs-string">"Received message: "</span> + message);
    }
}
</code></pre>
<p>In the above code, <code>KafkaProducerController</code> is a REST controller that exposes a <code>/publish</code> endpoint that can be used to send messages to the <code>test-topic</code> topic. The <code>KafkaConsumer</code> class is a simple Kafka consumer that listens to the <code>test-topic</code> topic and prints the received message to the console.</p>
<h2 id="heading-configuring-kafka-properties-in-spring-boot"><strong>Configuring Kafka Properties in Spring Boot</strong></h2>
<p>To configure Kafka properties in a Spring Boot application, we can use the <code>application.yml</code> or <code>application.properties</code> file. We can configure the Kafka properties as follows:</p>
<pre><code class="lang-yaml"><span class="hljs-attr">spring:</span>
  <span class="hljs-attr">kafka:</span>
    <span class="hljs-attr">bootstrap-servers:</span> <span class="hljs-string">localhost:9092</span>
</code></pre>
<p>In the above code, we are specifying the Kafka bootstrap servers that our application should connect to. We can also specify other Kafka properties, such as the group ID, security protocol, SSL settings, and more.</p>
<h2 id="heading-sending-messages-to-kafka"><strong>Sending Messages to Kafka</strong></h2>
<p>To send messages to Kafka, we can use the <code>KafkaTemplate</code> class provided by the Spring Kafka library. The <code>KafkaTemplate</code> class is a high-level abstraction for sending messages to Kafka topics.</p>
<pre><code class="lang-java"><span class="hljs-meta">@Autowired</span>
<span class="hljs-keyword">private</span> KafkaTemplate&lt;String, String&gt; kafkaTemplate;

<span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">sendMessage</span><span class="hljs-params">(String message)</span> </span>{
    kafkaTemplate.send(<span class="hljs-string">"test-topic"</span>, message);
}
</code></pre>
<p>In the above code, we are injecting a <code>KafkaTemplate</code> instance into our class using the <code>@Autowired</code> annotation. We can then use the <code>send</code> method to send a message to the <code>test-topic</code> topic.</p>
<h2 id="heading-consuming-messages-from-kafka"><strong>Consuming Messages from Kafka</strong></h2>
<p>To consume messages from Kafka, we can use the <code>@KafkaListener</code> annotation provided by the SpringKafka library. The <code>@KafkaListener</code> annotation is used to annotate a method that should be called when a new message is received on a specific Kafka topic.</p>
<pre><code class="lang-java"><span class="hljs-meta">@KafkaListener(topics = "test-topic", groupId = "test-group")</span>
<span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">consume</span><span class="hljs-params">(String message)</span> </span>{
    System.out.println(<span class="hljs-string">"Received message: "</span> + message);
}
</code></pre>
<p>In the above code, we are annotating a method with the <code>@KafkaListener</code> annotation. This method will be called when a new message is received on the <code>test-topic</code> topic. We are also specifying the group ID as <code>test-group</code>.</p>
<h2 id="heading-using-kafka-headers"><strong>Using Kafka Headers</strong></h2>
<p>Kafka headers are a key-value map that can be attached to messages. Headers can be used to add metadata to messages, such as correlation IDs, message IDs, or timestamps.</p>
<p>To add headers to a Kafka message, we can use the <code>ProducerRecord</code> class provided by the Kafka library.</p>
<pre><code class="lang-java"><span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">sendMessageWithHeaders</span><span class="hljs-params">(String message)</span> </span>{
    ProducerRecord&lt;String, String&gt; record = <span class="hljs-keyword">new</span> ProducerRecord&lt;&gt;(<span class="hljs-string">"test-topic"</span>, message);
    record.headers().add(<span class="hljs-string">"correlation-id"</span>, <span class="hljs-string">"12345"</span>.getBytes());
    kafkaTemplate.send(record);
}
</code></pre>
<p>In the above code, we are creating a new <code>ProducerRecord</code> instance and adding a header with the key <code>correlation-id</code> and the value <code>12345</code>. We can then send the message using the <code>kafkaTemplate</code>.</p>
<p>To read headers from a Kafka message, we can use the <code>@Header</code> annotation provided by the Spring Kafka library.</p>
<pre><code class="lang-java"><span class="hljs-meta">@KafkaListener(topics = "test-topic", groupId = "test-group")</span>
<span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">consumeWithHeaders</span><span class="hljs-params">(<span class="hljs-meta">@Payload</span> String message,
                               <span class="hljs-meta">@Header("correlation-id")</span> String correlationId)</span> </span>{
    System.out.println(<span class="hljs-string">"Received message: "</span> + message);
    System.out.println(<span class="hljs-string">"Correlation ID: "</span> + correlationId);
}
</code></pre>
<p>In the above code, we are annotating a method with the <code>@KafkaListener</code> annotation and specifying the <code>@Header</code> annotation to read the <code>correlation-id</code> header value.</p>
<h2 id="heading-using-kafka-transactions"><strong>Using Kafka Transactions</strong></h2>
<p>Kafka transactions provide atomicity and consistency guarantees when producing messages to Kafka. Transactions allow multiple Kafka producers to coordinate their actions to ensure that either all or none of the messages produced by a transaction are written to Kafka.</p>
<p>To use Kafka transactions in a Spring Boot application, we can use the <code>KafkaTransactionManager</code> provided by the Spring Kafka library.</p>
<pre><code class="lang-java"><span class="hljs-meta">@Bean</span>
<span class="hljs-function"><span class="hljs-keyword">public</span> KafkaTransactionManager&lt;String, String&gt; <span class="hljs-title">kafkaTransactionManager</span><span class="hljs-params">(ProducerFactory&lt;String, String&gt; producerFactory)</span> </span>{
    KafkaTransactionManager&lt;String, String&gt; transactionManager = <span class="hljs-keyword">new</span> KafkaTransactionManager&lt;&gt;(producerFactory);
    transactionManager.setTransactionSynchronization(SYNCHRONIZATION_ON_ACTUAL_TRANSACTION);
    <span class="hljs-keyword">return</span> transactionManager;
}
</code></pre>
<p>In the above code, we are creating a new <code>KafkaTransactionManager</code> instance and configuring it to use the <code>SYNCHRONIZATION_ON_ACTUAL_TRANSACTION</code> synchronization policy.</p>
<p>We can then use the <code>@Transactional</code> annotation provided by the Spring framework to wrap Kafka message production within a transaction.</p>
<pre><code class="lang-java"><span class="hljs-meta">@Transactional</span>
<span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">sendMessageInTransaction</span><span class="hljs-params">(String message)</span> </span>{
    kafkaTemplate.send(<span class="hljs-string">"test-topic"</span>, message);
}
</code></pre>
<p>In the above code, we are annotating the <code>sendMessageInTransaction</code> method with the <code>@Transactional</code> annotation. This ensures that the Kafka message is produced within a transaction.</p>
<h2 id="heading-conclusion"><strong>Conclusion</strong></h2>
<p>In this article, we have seen how to use Spring Boot with Apache Kafka to build event-driven systems. We started by discussing the benefits of using event-driven systems and Apache Kafka. We then saw how to configure Apache Kafka in a Spring Boot application using the <code>spring-kafka</code> library. We also saw how to send and consume messages from Kafka using the <code>KafkaTemplate</code> and <code>@KafkaListener</code> annotations. Finally, we discussed how to use Kafka headers and transactions in a Spring Boot application.</p>
<p>With the help of the Spring Kafka library, building event-driven systems with Apache Kafka has become much simpler and more manageable. By leveraging Spring Boot's autoconfiguration and dependency management capabilities, we can quickly develop and deploy robust and scalable event-driven systems.</p>
]]></content:encoded></item><item><title><![CDATA[Building Reactive Systems with Spring Boot: Leveraging Spring WebFlux and Reactor]]></title><description><![CDATA[Building Reactive Systems with Spring Boot: Leveraging Spring WebFlux and Reactor
In today's fast-paced world, where responsiveness and scalability are critical factors, building reactive systems has become a necessity. Reactive systems are those tha...]]></description><link>https://amrtechuniverse.com/building-reactive-systems-with-spring-boot-guide-spring-webflux-reactor</link><guid isPermaLink="true">https://amrtechuniverse.com/building-reactive-systems-with-spring-boot-guide-spring-webflux-reactor</guid><category><![CDATA[Springboot]]></category><category><![CDATA[Reactive Programming]]></category><category><![CDATA[springwebflux]]></category><category><![CDATA[Java]]></category><category><![CDATA[Reactor]]></category><dc:creator><![CDATA[Amr Khaled]]></dc:creator><pubDate>Fri, 24 Feb 2023 19:00:38 GMT</pubDate><content:encoded><![CDATA[<h1 id="heading-building-reactive-systems-with-spring-boot-leveraging-spring-webflux-and-reactor"><strong>Building Reactive Systems with Spring Boot: Leveraging Spring WebFlux and Reactor</strong></h1>
<p>In today's fast-paced world, where responsiveness and scalability are critical factors, building reactive systems has become a necessity. Reactive systems are those that can respond to events as soon as they occur, rather than waiting for a request to complete. This approach allows us to build systems that are more responsive, resilient, and scalable than traditional request-response systems.</p>
<p>In this article, we will see how to build reactive systems using Spring Boot, Spring WebFlux, and Reactor. We will start by discussing the benefits of reactive programming and the principles of the reactive manifesto. We will then dive into the specifics of building reactive systems using Spring Boot, Spring WebFlux, and Reactor, with plenty of code examples along the way.</p>
<h2 id="heading-what-is-reactive-programming">What is Reactive Programming?</h2>
<p>To understand reactive programming, it's important to understand the difference between synchronous and asynchronous programming models. In a synchronous programming model, a request is made and the program waits for a response before moving on to the next request. In contrast, an asynchronous programming model allows requests to be processed in parallel, with the program continuing to process requests while waiting for a response.</p>
<p>Reactive programming takes the asynchronous programming model a step further, by allowing us to process streams of data in a non-blocking way. This means that we can handle large volumes of data without blocking the program's main thread. Reactive programming is particularly useful in situations where we need to process large volumes of data in real-time, such as in a streaming data application.</p>
<p>Spring WebFlux is a Spring Framework module that provides support for building reactive web applications. It is built on top of the Reactive Streams specification, which defines a standard for asynchronous stream processing in Java. Spring WebFlux allows us to build non-blocking, reactive applications that can handle large volumes of requests with minimal resources.</p>
<p>Reactor is a Java library for building reactive applications. It provides two types of reactive streams: Flux and Mono. A Flux is a stream that can emit zero or more items, while a Mono is a stream that can emit zero or one item. Reactor provides a wide range of operators for manipulating these streams, allowing us to filter, transform, and combine them in a variety of ways.</p>
<p>By combining Spring WebFlux and Reactor, we can build highly responsive and scalable applications that can handle large volumes of requests with minimal resources. We can also use Spring Boot to simplify the process of building and deploying our applications, allowing us to focus on writing code rather than configuring infrastructure.</p>
<h2 id="heading-benefits-of-reactive-programming"><strong>Benefits of Reactive Programming</strong></h2>
<p>Reactive programming is an approach to programming that focuses on building systems that can react to events as they occur. Reactive systems are built using asynchronous and non-blocking programming models, allowing them to handle a large number of requests with fewer resources.</p>
<p>The benefits of reactive programming include:</p>
<ul>
<li><p>Responsiveness: Reactive systems can respond to events as they occur, rather than waiting for requests to complete.</p>
</li>
<li><p>Scalability: Reactive systems can handle a large number of requests with fewer resources.</p>
</li>
<li><p>Resilience: Reactive systems can handle failure more gracefully and recover more quickly.</p>
</li>
</ul>
<h2 id="heading-principles-of-the-reactive-manifesto"><strong>Principles of the Reactive Manifesto</strong></h2>
<p>The Reactive Manifesto is a document that outlines the principles of reactive programming. These principles are:</p>
<ul>
<li><p>Responsive: The system should respond in a timely manner to user requests and events.</p>
</li>
<li><p>Resilient: The system should be able to handle and recover from failures.</p>
</li>
<li><p>Elastic: The system should be able to scale up or down depending on the load.</p>
</li>
<li><p>Message-driven: The system should be designed around messages and events, rather than synchronous method calls.</p>
</li>
</ul>
<h2 id="heading-building-reactive-systems-with-spring-boot"><strong>Building Reactive Systems with Spring Boot</strong></h2>
<p>Spring Boot is a popular framework for building enterprise applications. It provides a range of features that simplify the development and deployment of applications, including auto-configuration, embedded servers, and production-ready metrics.</p>
<p>Spring WebFlux is a Spring framework for building reactive web applications. It provides a non-blocking programming model that can handle a large number of requests with fewer resources.</p>
<p>Reactor is a reactive programming library for the JVM. It provides a range of abstractions for building reactive systems, including Flux and Mono for handling streams of data.</p>
<p>To build reactive systems with Spring Boot, we need to follow these steps:</p>
<ol>
<li><p>Configure the Spring WebFlux application.</p>
</li>
<li><p>Define the reactive endpoints.</p>
</li>
<li><p>Use Reactor to handle the streams of data.</p>
</li>
</ol>
<p>Let's see how to do each of these steps in detail.</p>
<h3 id="heading-step-1-configure-the-spring-webflux-application"><strong>Step 1: Configure the Spring WebFlux application</strong></h3>
<p>To configure the Spring WebFlux application, we need to add the <code>spring-webflux</code> dependency to our project. We also need to configure the <code>WebFluxConfigurer</code> to set up the reactive infrastructure.</p>
<pre><code class="lang-xml"><span class="hljs-tag">&lt;<span class="hljs-name">dependency</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">groupId</span>&gt;</span>org.springframework.boot<span class="hljs-tag">&lt;/<span class="hljs-name">groupId</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">artifactId</span>&gt;</span>spring-webflux<span class="hljs-tag">&lt;/<span class="hljs-name">artifactId</span>&gt;</span>
<span class="hljs-tag">&lt;/<span class="hljs-name">dependency</span>&gt;</span>
</code></pre>
<pre><code class="lang-java"><span class="hljs-meta">@Configuration</span>
<span class="hljs-meta">@EnableWebFlux</span>
<span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">WebFluxConfig</span> <span class="hljs-keyword">implements</span> <span class="hljs-title">WebFluxConfigurer</span> </span>{
    <span class="hljs-meta">@Override</span>
    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">configureHttpMessageCodecs</span><span class="hljs-params">(ServerCodecConfigurer configurer)</span> </span>{
        configurer.defaultCodecs().jackson2JsonEncoder(<span class="hljs-keyword">new</span> Jackson2JsonEncoder());
        configurer.defaultCodecs().jackson2JsonDecoder(<span class="hljs-keyword">new</span> Jackson2JsonDecoder());
    }
}
</code></pre>
<p>In the above code, we are enabling the Spring WebFlux infrastructure by annotating the configuration class with <code>@EnableWebFlux</code>. We are also configuring the <code>ServerCodecConfigurer</code> to use the Jackson library for encoding and decoding JSON data.</p>
<h3 id="heading-step-2-define-the-reactive-endpoints"><strong>Step 2: Define the reactive endpoints</strong></h3>
<p>To define the reactive endpoints, we need to create a controller and annotate its methods with the appropriate annotations. We can use the <code>@RestController</code> annotation to indicate that this controller will handle HTTP requests, and the <code>@GetMapping</code> annotation to define the endpoints.</p>
<pre><code class="lang-java"><span class="hljs-meta">@RestController</span>
<span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">ReactiveController</span> </span>{
    <span class="hljs-meta">@GetMapping("/reactive")</span>
    <span class="hljs-function"><span class="hljs-keyword">public</span> Flux&lt;String&gt; <span class="hljs-title">getReactiveData</span><span class="hljs-params">()</span> </span>{
        <span class="hljs-keyword">return</span> Flux.just(<span class="hljs-string">"Reactive"</span>, <span class="hljs-string">"Systems"</span>, <span class="hljs-string">"Are"</span>, <span class="hljs-string">"Awesome"</span>);
    }
}
</code></pre>
<p>In the above code, we are defining a reactive endpoint that returns a <code>Flux</code> of strings. A <code>Flux</code> is a reactive stream that can emit zero or more items. In this case, we are emitting four strings: "Reactive", "Systems", "Are", and "Awesome".</p>
<h3 id="heading-step-3-use-reactor-to-handle-the-streams-of-data"><strong>Step 3: Use Reactor to handle the streams of data</strong></h3>
<p>To handle the streams of data, we need to use Reactor. Reactor provides two types of reactive streams: <code>Flux</code> and <code>Mono</code>. A <code>Flux</code> can emit zero or more items, while a <code>Mono</code> can emit zero or one item.</p>
<p>We can use Reactor to process the streams of data in a variety of ways, including filtering, mapping, and reducing. Here's an example of how to map the strings emitted by the <code>Flux</code>:</p>
<pre><code class="lang-java">Flux&lt;String&gt; reactiveData = Flux.just(<span class="hljs-string">"Reactive"</span>, <span class="hljs-string">"Systems"</span>, <span class="hljs-string">"Are"</span>, <span class="hljs-string">"Awesome"</span>);
Flux&lt;String&gt; mappedData = reactiveData.map(s -&gt; s.toUpperCase());
</code></pre>
<p>In the above code, we are creating a <code>Flux</code> of strings and then using the <code>map</code> operator to transform the strings to uppercase.</p>
<p>We can also use Reactor to combine multiple streams of data. Here's an example of how to combine two <code>Flux</code> streams:</p>
<pre><code class="lang-java">Flux&lt;String&gt; flux1 = Flux.just(<span class="hljs-string">"Reactive"</span>, <span class="hljs-string">"Systems"</span>);
Flux&lt;String&gt; flux2 = Flux.just(<span class="hljs-string">"Are"</span>, <span class="hljs-string">"Awesome"</span>);
Flux&lt;String&gt; combined = Flux.zip(flux1, flux2).map(t -&gt; t.getT1() + <span class="hljs-string">" "</span> + t.getT2());
</code></pre>
<p>In the above code, we are creating two <code>Flux</code> streams and then using the <code>zip</code> operator to combine them. We are then using the <code>map</code> operator to concatenate the two strings emitted by each <code>Flux</code>.</p>
<h3 id="heading-step-4-manipulating-data-streams-with-reactor-operators-and-debugging-reactive-systems">Step 4: Manipulating Data Streams with Reactor Operators and Debugging Reactive Systems</h3>
<p>Step 3 showed us how to use Reactor to handle the streams of data in our reactive system. In this step, we'll take a closer look at some of the operators provided by Reactor and how we can use them to manipulate our data streams.</p>
<p>One useful operator is the <code>map</code> operator, which allows us to transform the data in our streams. For example, suppose we have a stream of numbers and we want to multiply each number by 2. We can use the <code>map</code> operator to achieve this:</p>
<pre><code class="lang-java">Flux&lt;Integer&gt; numbers = Flux.just(<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>, <span class="hljs-number">4</span>, <span class="hljs-number">5</span>);
Flux&lt;Integer&gt; doubled = numbers.map(n -&gt; n * <span class="hljs-number">2</span>);
</code></pre>
<p>In this example, <code>doubled</code> is a new stream that emits the values 2, 4, 6, 8, and 10. We can chain multiple operators together to perform more complex transformations:</p>
<pre><code class="lang-java">Flux&lt;Integer&gt; numbers = Flux.just(<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>, <span class="hljs-number">4</span>, <span class="hljs-number">5</span>);
Flux&lt;String&gt; strings = numbers
    .filter(n -&gt; n % <span class="hljs-number">2</span> == <span class="hljs-number">0</span>)
    .map(n -&gt; <span class="hljs-string">"Number "</span> + n);
</code></pre>
<p>In this example, we filter out the odd numbers and then map the even numbers to strings with a prefix of "Number ".</p>
<p>Another useful operator is the <code>flatMap</code> operator, which allows us to transform each element in a stream into one or more elements in a new stream. For example, suppose we have a stream of words and we want to split each word into its individual characters:</p>
<pre><code class="lang-java">Flux&lt;String&gt; words = Flux.just(<span class="hljs-string">"hello"</span>, <span class="hljs-string">"world"</span>);
Flux&lt;String&gt; characters = words.flatMap(word -&gt; Flux.fromArray(word.split(<span class="hljs-string">""</span>)));
</code></pre>
<p>In this example, <code>characters</code> is a new stream that emits the individual characters in the words "hello" and "world".</p>
<p>Debugging reactive systems can be challenging, as the code is often asynchronous and non-blocking. Fortunately, Spring Boot provides some tools to help us debug our reactive code. One useful tool is the <code>log</code> operator, which allows us to log the events in our streams. For example, we can add a <code>log</code> operator to our stream of numbers:</p>
<pre><code class="lang-java">Flux&lt;Integer&gt; numbers = Flux.just(<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>, <span class="hljs-number">4</span>, <span class="hljs-number">5</span>);
numbers
    .log()
    .subscribe();
</code></pre>
<p>In this example, we add the <code>log</code> operator to our stream of numbers and then subscribe to it. The <code>log</code> operator will print out the events in the stream, including when elements are emitted, when errors occur, and when the stream is completed.</p>
<h2 id="heading-conclusion"><strong>Conclusion</strong></h2>
<p>Reactive programming is an approach to programming that focuses on building systems that can react to events as they occur. Reactive systems are built using asynchronous and non-blocking programming models, allowing them to handle a large number of requests with fewer resources.</p>
<p>Spring Boot, Spring WebFlux, and Reactor provide the tools we need to build reactive systems. With these technologies, we can build systems that are more responsive, resilient, and scalable than traditional request-response systems. By following the principles of the Reactive Manifesto and using the best practices for building reactive systems, we can create applications that meet the demands of today's fast-paced world.</p>
]]></content:encoded></item><item><title><![CDATA[State Machine Diagrams in Spring Boot: Usage and Implementation]]></title><description><![CDATA[State Machine Diagrams in Spring Boot: Usage and Implementation
State machine diagrams are a powerful tool for modeling complex behavior in software systems. In Spring Boot, the State Machine Framework provides an easy way to implement state machine ...]]></description><link>https://amrtechuniverse.com/state-machine-diagrams-in-spring-boot-usage-and-implementation</link><guid isPermaLink="true">https://amrtechuniverse.com/state-machine-diagrams-in-spring-boot-usage-and-implementation</guid><category><![CDATA[Springboot]]></category><category><![CDATA[state-machines]]></category><category><![CDATA[Java]]></category><category><![CDATA[Spring]]></category><dc:creator><![CDATA[Amr Khaled]]></dc:creator><pubDate>Fri, 24 Feb 2023 14:02:01 GMT</pubDate><content:encoded><![CDATA[<h1 id="heading-state-machine-diagrams-in-spring-boot-usage-and-implementation"><strong>State Machine Diagrams in Spring Boot: Usage and Implementation</strong></h1>
<p>State machine diagrams are a powerful tool for modeling complex behavior in software systems. In Spring Boot, the State Machine Framework provides an easy way to implement state machine diagrams in Java.</p>
<h2 id="heading-what-is-a-state-machine-diagram"><strong>What is a State Machine Diagram?</strong></h2>
<p>A state machine diagram is a graphical representation of a finite-state machine, which is a mathematical model of computation. In software engineering, state machine diagrams are commonly used to model complex behavior in software systems. The diagram consists of states, transitions, and events, which represent the various possible states of the system and how it transitions between those states.</p>
<h2 id="heading-the-state-machine-framework-in-spring-boot"><strong>The State Machine Framework in Spring Boot</strong></h2>
<p>Spring Boot provides a State Machine Framework, which is a flexible and extensible way to implement state machine diagrams in Java. The framework is built on top of the Spring Framework and provides a variety of features, including:</p>
<ul>
<li><p>Easy configuration and integration with Spring Boot applications</p>
</li>
<li><p>Support for multiple state machine instances</p>
</li>
<li><p>Hierarchical state machines</p>
</li>
<li><p>Support for triggers and guards</p>
</li>
<li><p>Support for state machine listeners and error handling</p>
</li>
</ul>
<h2 id="heading-usage"><strong>Usage</strong></h2>
<p>To use the State Machine Framework in Spring Boot, you first need to add the following dependency to your <code>pom.xml</code> file:</p>
<pre><code class="lang-xml"><span class="hljs-tag">&lt;<span class="hljs-name">dependency</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">groupId</span>&gt;</span>org.springframework.statemachine<span class="hljs-tag">&lt;/<span class="hljs-name">groupId</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">artifactId</span>&gt;</span>spring-statemachine-core<span class="hljs-tag">&lt;/<span class="hljs-name">artifactId</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">version</span>&gt;</span>2.1.3.RELEASE<span class="hljs-tag">&lt;/<span class="hljs-name">version</span>&gt;</span>
<span class="hljs-tag">&lt;/<span class="hljs-name">dependency</span>&gt;</span>
</code></pre>
<p>Once you have added the dependency, you can create a new state machine by implementing the <code>StateMachineConfigurer</code> interface:</p>
<pre><code class="lang-java"><span class="hljs-meta">@Configuration</span>
<span class="hljs-meta">@EnableStateMachine</span>
<span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">StateMachineConfig</span> <span class="hljs-keyword">extends</span> <span class="hljs-title">StateMachineConfigurerAdapter</span>&lt;<span class="hljs-title">String</span>, <span class="hljs-title">String</span>&gt; </span>{

    <span class="hljs-meta">@Override</span>
    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">configure</span><span class="hljs-params">(StateMachineStateConfigurer&lt;String, String&gt; states)</span> <span class="hljs-keyword">throws</span> Exception </span>{
        states.withStates()
            .initial(<span class="hljs-string">"START"</span>)
            .state(<span class="hljs-string">"STATE1"</span>)
            .state(<span class="hljs-string">"STATE2"</span>)
            .end(<span class="hljs-string">"END"</span>);
    }

    <span class="hljs-meta">@Override</span>
    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">configure</span><span class="hljs-params">(StateMachineTransitionConfigurer&lt;String, String&gt; transitions)</span> <span class="hljs-keyword">throws</span> Exception </span>{
        transitions.withExternal()
            .source(<span class="hljs-string">"START"</span>).target(<span class="hljs-string">"STATE1"</span>).event(<span class="hljs-string">"EVENT1"</span>)
            .and()
            .withExternal()
            .source(<span class="hljs-string">"STATE1"</span>).target(<span class="hljs-string">"STATE2"</span>).event(<span class="hljs-string">"EVENT2"</span>)
            .and()
            .withExternal()
            .source(<span class="hljs-string">"STATE2"</span>).target(<span class="hljs-string">"END"</span>).event(<span class="hljs-string">"EVENT3"</span>);
    }
}
</code></pre>
<p>In this example, we are creating a state machine with four states: START, STATE1, STATE2, and END. We are also defining three events: EVENT1, EVENT2, and EVENT3. The <code>configure</code> method is used to define the transitions between the states.</p>
<h2 id="heading-full-code-example"><strong>Full Code Example</strong></h2>
<p>Let's consider a use case where we have a simple order processing system. The order can be in one of three states: NEW, PAID, or FULFILLED. When an order is created, it starts in the NEW state. When the order is paid, it transitions to the PAID state. When the order is fulfilled, it transitions to the FULFILLED state. We can model this system using a state machine diagram.</p>
<p>To implement this state machine in Spring Boot, we can create a new Spring Boot project and add the following dependencies to the <code>pom.xml</code> file:</p>
<pre><code class="lang-xml"><span class="hljs-tag">&lt;<span class="hljs-name">dependencies</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">dependency</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">groupId</span>&gt;</span>org.springframework.boot<span class="hljs-tag">&lt;/<span class="hljs-name">groupId</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">artifactId</span>&gt;</span>spring-boot-starter-web<span class="hljs-tag">&lt;/<span class="hljs-name">artifactId</span>&gt;</span>
    <span class="hljs-tag">&lt;/<span class="hljs-name">dependency</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">dependency</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">groupId</span>&gt;</span>org.springframework.statemachine<span class="hljs-tag">&lt;/<span class="hljs-name">groupId</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">artifactId</span>&gt;</span>spring-statemachine-core<span class="hljs-tag">&lt;/<span class="hljs-name">artifactId</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">version</span>&gt;</span>3.2.0<span class="hljs-tag">&lt;/<span class="hljs-name">version</span>&gt;</span>
    <span class="hljs-tag">&lt;/<span class="hljs-name">dependency</span>&gt;</span>
<span class="hljs-tag">&lt;/<span class="hljs-name">dependencies</span>&gt;</span>
</code></pre>
<p>In this example, we are adding two dependencies to our project: <code>spring-boot-starter-web</code>, which provides the necessary components for building a web application, and <code>spring-statemachine-core</code>, which provides the State Machine Framework.</p>
<p>Note that we are using version 3.2.0 of the <code>spring-statemachine-core</code> dependency. This is the latest stable version at the time of writing, but you should always check for the latest version available for your project.</p>
<p>We can then create a new Java class called <code>OrderStateMachineConfig</code> and implement the <code>StateMachineConfigurer</code> interface. We will define three states and three events, and we will configure the transitions between those states:</p>
<pre><code class="lang-java"><span class="hljs-meta">@Configuration</span>
<span class="hljs-meta">@EnableStateMachine</span>
<span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">OrderStateMachineConfig</span> <span class="hljs-keyword">extends</span> <span class="hljs-title">StateMachineConfigurerAdapter</span>&lt;<span class="hljs-title">OrderState</span>, <span class="hljs-title">OrderEvent</span>&gt; </span>{

    <span class="hljs-meta">@Override</span>
    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">configure</span><span class="hljs-params">(StateMachineStateConfigurer&lt;OrderState, OrderEvent&gt; states)</span> <span class="hljs-keyword">throws</span> Exception </span>{
        states.withStates()
                .initial(OrderState.NEW)
                .state(OrderState.PAID)
                .end(OrderState.FULFILLED);
    }

    <span class="hljs-meta">@Override</span>
    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">configure</span><span class="hljs-params">(StateMachineTransitionConfigurer&lt;OrderState, OrderEvent&gt; transitions)</span> <span class="hljs-keyword">throws</span> Exception </span>{
        transitions.withExternal()
                .source(OrderState.NEW).target(OrderState.PAID).event(OrderEvent.PAYMENT)
                .and()
                .withExternal()
                .source(OrderState.PAID).target(OrderState.FULFILLED).event(OrderEvent.FULFILLMENT);
    }

    <span class="hljs-meta">@Bean</span>
    <span class="hljs-function"><span class="hljs-keyword">public</span> StateMachineListener&lt;OrderState, OrderEvent&gt; <span class="hljs-title">listener</span><span class="hljs-params">()</span> </span>{
        <span class="hljs-keyword">return</span> <span class="hljs-keyword">new</span> StateMachineListenerAdapter&lt;&gt;() {
            <span class="hljs-meta">@Override</span>
            <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">transition</span><span class="hljs-params">(Transition&lt;OrderState, OrderEvent&gt; transition)</span> </span>{
                System.out.println(<span class="hljs-string">"Transitioning from "</span> + transition.getSource().getId() + <span class="hljs-string">" to "</span> + transition.getTarget().getId());
            }
        };
    }

    <span class="hljs-meta">@Bean</span>
    <span class="hljs-function"><span class="hljs-keyword">public</span> StateMachineErrorHandler&lt;OrderState, OrderEvent&gt; <span class="hljs-title">errorHandler</span><span class="hljs-params">()</span> </span>{
        <span class="hljs-keyword">return</span> <span class="hljs-keyword">new</span> StateMachineErrorHandlerAdapter&lt;&gt;() {
            <span class="hljs-meta">@Override</span>
            <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">error</span><span class="hljs-params">(StateMachine&lt;OrderState, OrderEvent&gt; stateMachine, Exception exception)</span> </span>{
                System.out.println(<span class="hljs-string">"Error occurred in state machine: "</span> + exception.getMessage());
            }
        };
    }

}
</code></pre>
<p>In this code, we are defining an <code>OrderState</code> enum and an <code>OrderEvent</code> enum, which represent the states and events in our state machine. We are also implementing two methods from the <code>StateMachineConfigurer</code> interface: <code>configure(StateMachineStateConfigurer)</code> and <code>configure(StateMachineTransitionConfigurer)</code>. In these methods, we are defining the states and transitions in our state machine.</p>
<p>We have also defined two additional beans: a <code>StateMachineListener</code> and a <code>StateMachineErrorHandler</code>. The <code>listener</code> bean is used to listen for state transitions and print them to the console, while the <code>errorHandler</code> bean is used to handle any errors that occur in the state machine.</p>
<p>Finally, we can create a REST endpoint to test our state machine. We will create a new controller called <code>OrderController</code> with a <code>POST</code> method that accepts a JSON payload containing the order details:</p>
<pre><code class="lang-java"><span class="hljs-meta">@RestController</span>
<span class="hljs-meta">@RequestMapping("/orders")</span>
<span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">OrderController</span> </span>{

    <span class="hljs-keyword">private</span> <span class="hljs-keyword">final</span> StateMachine&lt;OrderState, OrderEvent&gt; stateMachine;

    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-title">OrderController</span><span class="hljs-params">(StateMachine&lt;OrderState, OrderEvent&gt; stateMachine)</span> </span>{
        <span class="hljs-keyword">this</span>.stateMachine = stateMachine;
    }

    <span class="hljs-meta">@PostMapping</span>
    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">createOrder</span><span class="hljs-params">(<span class="hljs-meta">@RequestBody</span> Order order)</span> </span>{
        stateMachine.start();
        stateMachine.sendEvent(OrderEvent.PAYMENT);
        stateMachine.sendEvent(OrderEvent.FULFILLMENT);
    }

}
</code></pre>
<p>In this code, we are injecting an instance of the <code>StateMachine</code> into the controller using constructor injection. We are also defining a <code>POST</code> method that starts the state machine and sends two events: <code>PAYMENT</code> and <code>FULFILLMENT</code>.</p>
<h2 id="heading-conclusion"><strong>Conclusion</strong></h2>
<p>In conclusion, the State Machine Framework in Spring Boot provides a powerful way to model complex behavior in software systems. By defining states, events, and transitions, we can easily create a state machine that can handle various scenarios in our application.</p>
<p>In this article, we have seen how to define a state machine using the State Machine Framework and create a simple example to illustrate its usage. With this knowledge, developers can implement state machines in their projects to handle various scenarios with ease.</p>
]]></content:encoded></item><item><title><![CDATA[SOLID Principles in Spring Boot: A Comprehensive Guide]]></title><description><![CDATA[SOLID Principles in Spring Boot: A Comprehensive Guide
SOLID is an acronym for the 5 principles of object-oriented design that promote software maintainability, scalability, and readability. These principles were introduced by Robert C. Martin and ha...]]></description><link>https://amrtechuniverse.com/solid-principles-in-spring-boot</link><guid isPermaLink="true">https://amrtechuniverse.com/solid-principles-in-spring-boot</guid><category><![CDATA[SOLID principles]]></category><category><![CDATA[Springboot]]></category><category><![CDATA[Java]]></category><category><![CDATA[Spring]]></category><category><![CDATA[Spring framework]]></category><dc:creator><![CDATA[Amr Khaled]]></dc:creator><pubDate>Sat, 11 Feb 2023 11:34:10 GMT</pubDate><content:encoded><![CDATA[<h1 id="heading-solid-principles-in-spring-boot-a-comprehensive-guide"><strong>SOLID Principles in Spring Boot: A Comprehensive Guide</strong></h1>
<p>SOLID is an acronym for the 5 principles of object-oriented design that promote software maintainability, scalability, and readability. These principles were introduced by Robert C. Martin and have since become a cornerstone of software development best practices.</p>
<p>In this article, we will explore each of the SOLID principles and demonstrate how to implement them in a Spring Boot application.</p>
<h2 id="heading-single-responsibility-principle-srp"><strong>Single Responsibility Principle (SRP)</strong></h2>
<p>The Single Responsibility Principle states that a class should have only one reason to change. In other words, a class should only have one responsibility.</p>
<p>To implement SRP in Spring Boot, we can create separate classes for different responsibilities. For example, consider a scenario where we have a class that handles both user authentication and user management. To follow the SRP, we can separate these responsibilities into two separate classes: <code>AuthenticationService</code> and <code>UserManagementService</code>.</p>
<pre><code class="lang-java"><span class="hljs-meta">@Service</span>
<span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">AuthenticationService</span> </span>{
  <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">boolean</span> <span class="hljs-title">authenticate</span><span class="hljs-params">(String username, String password)</span> </span>{
    <span class="hljs-comment">// authentication logic</span>
  }
}

<span class="hljs-meta">@Service</span>
<span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">UserManagementService</span> </span>{
  <span class="hljs-function"><span class="hljs-keyword">public</span> User <span class="hljs-title">createUser</span><span class="hljs-params">(User user)</span> </span>{
    <span class="hljs-comment">// user management logic</span>
  }

  <span class="hljs-function"><span class="hljs-keyword">public</span> User <span class="hljs-title">updateUser</span><span class="hljs-params">(User user)</span> </span>{
    <span class="hljs-comment">// user management logic</span>
  }

  <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">deleteUser</span><span class="hljs-params">(Long id)</span> </span>{
    <span class="hljs-comment">// user management logic</span>
  }
}
</code></pre>
<p>Adhering to SRP results in code that is more maintainable and easier to understand, as responsibilities are separated into different classes.</p>
<h2 id="heading-openclosed-principle-ocp"><strong>Open/Closed Principle (OCP)</strong></h2>
<p>The Open/Closed Principle states that a class should be open for extension but closed for modification. In other words, a class should be designed in such a way that new functionality can be added without modifying existing code.</p>
<p>To implement OCP in Spring Boot, we can use the Template Method pattern. The Template Method pattern allows us to define a basic algorithm in a base class and then allow subclasses to provide specific implementations.</p>
<pre><code class="lang-java"><span class="hljs-keyword">public</span> <span class="hljs-keyword">abstract</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">PaymentService</span> </span>{
  <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">processPayment</span><span class="hljs-params">(Order order)</span> </span>{
    validateOrder(order);
    processPayment(order);
  }

  <span class="hljs-function"><span class="hljs-keyword">protected</span> <span class="hljs-keyword">abstract</span> <span class="hljs-keyword">void</span> <span class="hljs-title">validateOrder</span><span class="hljs-params">(Order order)</span></span>;
  <span class="hljs-function"><span class="hljs-keyword">protected</span> <span class="hljs-keyword">abstract</span> <span class="hljs-keyword">void</span> <span class="hljs-title">processPayment</span><span class="hljs-params">(Order order)</span></span>;
}

<span class="hljs-meta">@Service</span>
<span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">CreditCardPaymentService</span> <span class="hljs-keyword">extends</span> <span class="hljs-title">PaymentService</span> </span>{
  <span class="hljs-function"><span class="hljs-keyword">protected</span> <span class="hljs-keyword">void</span> <span class="hljs-title">validateOrder</span><span class="hljs-params">(Order order)</span> </span>{
    <span class="hljs-comment">// validate credit card payment</span>
  }

  <span class="hljs-function"><span class="hljs-keyword">protected</span> <span class="hljs-keyword">void</span> <span class="hljs-title">processPayment</span><span class="hljs-params">(Order order)</span> </span>{
    <span class="hljs-comment">// process credit card payment</span>
  }
}

<span class="hljs-meta">@Service</span>
<span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">PayPalPaymentService</span> <span class="hljs-keyword">extends</span> <span class="hljs-title">PaymentService</span> </span>{
  <span class="hljs-function"><span class="hljs-keyword">protected</span> <span class="hljs-keyword">void</span> <span class="hljs-title">validateOrder</span><span class="hljs-params">(Order order)</span> </span>{
    <span class="hljs-comment">// validate PayPal payment</span>
  }

  <span class="hljs-function"><span class="hljs-keyword">protected</span> <span class="hljs-keyword">void</span> <span class="hljs-title">processPayment</span><span class="hljs-params">(Order order)</span> </span>{
    <span class="hljs-comment">// process PayPal payment</span>
  }
}
</code></pre>
<p>By using the Template Method pattern, we can add new payment services without modifying existing code, thus adhering to the OCP.</p>
<h2 id="heading-liskov-substitution-principle-lsp"><strong>Liskov Substitution Principle (LSP)</strong></h2>
<p>The Liskov Substitution Principle states that objects of a superclass should be able to be replaced with objects of a subclass without affecting the correctness of the program. This means that if a program uses a base class, it should be able to work with any of its subclasses without modification.</p>
<p>In Spring Boot, we can implement the LSP by using inheritance and polymorphism. For example, consider a scenario where we have a base class <code>Animal</code> and two subclasses <code>Dog</code> and <code>Cat</code>.</p>
<pre><code class="lang-java"><span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Animal</span> </span>{
  <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">makeSound</span><span class="hljs-params">()</span> </span>{
    <span class="hljs-comment">// default sound implementation</span>
  }
}

<span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Dog</span> <span class="hljs-keyword">extends</span> <span class="hljs-title">Animal</span> </span>{
  <span class="hljs-meta">@Override</span>
  <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">makeSound</span><span class="hljs-params">()</span> </span>{
    System.out.println(<span class="hljs-string">"Bark"</span>);
  }
}

<span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Cat</span> <span class="hljs-keyword">extends</span> <span class="hljs-title">Animal</span> </span>{
  <span class="hljs-meta">@Override</span>
  <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">makeSound</span><span class="hljs-params">()</span> </span>{
    System.out.println(<span class="hljs-string">"Meow"</span>);
  }
}
</code></pre>
<p>In this example, the <code>Animal</code> class defines the behavior of making a sound, while the <code>Dog</code> and <code>Cat</code> classes provide their implementation of this behavior. When we use the <code>Animal</code> class in our program, we can substitute it with either a <code>Dog</code> or <code>Cat</code> object and the program will still work as expected.</p>
<p>Adhering to the LSP leads to more flexible and scalable code, as it allows us to make changes to the implementation of a class without affecting the rest of the program.</p>
<h2 id="heading-interface-segregation-principle-isp"><strong>Interface Segregation Principle (ISP)</strong></h2>
<p>The Interface Segregation Principle states that a class should not be forced to implement interfaces it does not use. In other words, a class should only be required to implement the methods that are relevant to its behavior.</p>
<p>To implement the ISP in Spring Boot, we can create multiple, smaller interfaces for different responsibilities instead of a single, large interface.</p>
<pre><code class="lang-java"><span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">interface</span> <span class="hljs-title">PaymentService</span> </span>{
  <span class="hljs-function"><span class="hljs-keyword">void</span> <span class="hljs-title">processPayment</span><span class="hljs-params">(Order order)</span></span>;
}

<span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">interface</span> <span class="hljs-title">RefundService</span> </span>{
  <span class="hljs-function"><span class="hljs-keyword">void</span> <span class="hljs-title">processRefund</span><span class="hljs-params">(Order order)</span></span>;
}

<span class="hljs-meta">@Service</span>
<span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">PayPalPaymentService</span> <span class="hljs-keyword">implements</span> <span class="hljs-title">PaymentService</span>, <span class="hljs-title">RefundService</span> </span>{
  <span class="hljs-meta">@Override</span>
  <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">processPayment</span><span class="hljs-params">(Order order)</span> </span>{
    <span class="hljs-comment">// payment processing logic</span>
  }

  <span class="hljs-meta">@Override</span>
  <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">processRefund</span><span class="hljs-params">(Order order)</span> </span>{
    <span class="hljs-comment">// refund processing logic</span>
  }
}
</code></pre>
<p>By creating separate interfaces for different responsibilities, we ensure that classes only implement the methods they need, making the code more maintainable and readable.</p>
<h2 id="heading-dependency-inversion-principle-dip"><strong>Dependency Inversion Principle (DIP)</strong></h2>
<p>The Dependency Inversion Principle states that high-level modules should not depend on low-level modules, but both should depend on abstractions. In other words, our code should depend on abstractions, not on concrete implementations.</p>
<p>To implement the DIP in Spring Boot, we can use dependency injection and inversion of control. For example, consider a scenario where we have a class <code>PaymentController</code> that depends on a <code>PaymentService</code>.</p>
<pre><code class="lang-java"><span class="hljs-meta">@RestController</span>
<span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">PaymentController</span> </span>{
  <span class="hljs-keyword">private</span> <span class="hljs-keyword">final</span> PaymentService paymentService;

  <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-title">PaymentController</span><span class="hljs-params">(PaymentService paymentService)</span> </span>{
    <span class="hljs-keyword">this</span>.paymentService = paymentService;
  }

  <span class="hljs-meta">@PostMapping("/pay")</span>
  <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">pay</span><span class="hljs-params">(<span class="hljs-meta">@RequestBody</span> Order order)</span> </span>{
    paymentService.processPayment(order);
  }
}
</code></pre>
<p>In this example, the <code>PaymentController</code> class depends on the <code>PaymentService</code> abstraction. We can use dependency injection to provide a concrete implementation of the <code>PaymentService</code> interface, such as <code>PayPalPaymentService</code>.</p>
<pre><code class="lang-java"><span class="hljs-meta">@Service</span>
<span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">PayPalPaymentService</span> <span class="hljs-keyword">implements</span> <span class="hljs-title">PaymentService</span> </span>{
  <span class="hljs-meta">@Override</span>
  <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">processPayment</span><span class="hljs-params">(Order order)</span> </span>{
    <span class="hljs-comment">// payment processing logic</span>
  }
}
</code></pre>
<p>By depending on an abstraction instead of a concrete implementation, we can easily switch to a different payment service without affecting the rest of our code. This makes our code more flexible and maintainable, as changes in the implementation of a service can be made without affecting the code that uses it.</p>
<h2 id="heading-conclusion"><strong>Conclusion</strong></h2>
<p>The SOLID principles are a set of guidelines for writing maintainable, scalable, and flexible code. By following these principles, we can write code that is easy to understand, modify, and test, leading to faster development and lower maintenance costs.</p>
<p>In this article, we covered Single Responsibility Principle (SRP), Open/Closed Principle (OCP), Liskov Substitution Principle (LSP), Interface Segregation Principle (ISP), and Dependency Inversion Principle (DIP) and provided examples of how to implement them in Spring Boot. By following these principles, we can create applications that are easy to maintain and evolve.</p>
]]></content:encoded></item><item><title><![CDATA[Understanding Spring Security: Authentication, Authorization, Custom Roles & External Database Integration]]></title><description><![CDATA[Introduction to Spring Security
Spring Security is a powerful and highly customizable authentication and access-control framework for Java-based applications. It is a project under the Spring Framework and provides a comprehensive security solution f...]]></description><link>https://amrtechuniverse.com/spring-security-authentication-authorization-custom-roles</link><guid isPermaLink="true">https://amrtechuniverse.com/spring-security-authentication-authorization-custom-roles</guid><category><![CDATA[Springboot]]></category><category><![CDATA[Spring]]></category><category><![CDATA[Spring framework]]></category><category><![CDATA[Java]]></category><category><![CDATA[spring security]]></category><dc:creator><![CDATA[Amr Khaled]]></dc:creator><pubDate>Wed, 01 Feb 2023 11:00:39 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1675023114312/113d3f59-4a3c-4aa0-807c-8cfa4e972b3d.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<h1 id="heading-introduction-to-spring-security"><strong>Introduction to Spring Security</strong></h1>
<p>Spring Security is a powerful and highly customizable authentication and access-control framework for Java-based applications. It is a project under the Spring Framework and provides a comprehensive security solution for both web and non-web applications. With Spring Security, developers can easily secure their applications by defining security rules, implementing authentication and authorization mechanisms, and handling access-control decisions.</p>
<p>In this article, we will discuss the basics of Spring Security and how to set it up in a web application. We will also go over some of the key features and capabilities of the framework, such as authentication and authorization, and how to secure different types of resources in an application.</p>
<h2 id="heading-setting-up-spring-security-in-a-web-application"><strong>Setting up Spring Security in a Web Application</strong></h2>
<p>To set up Spring Security in a web application, we need to add the Spring Security dependencies to our project. The easiest way to do this is to use the Spring Initializer tool, which can generate a basic project structure with the necessary dependencies.</p>
<p>Once the dependencies are added, we need to configure Spring Security in our application. This can be done by creating a configuration class that extends the <code>WebSecurityConfigurerAdapter</code> class and overrides its methods.</p>
<p>Here is an example of a basic configuration class:</p>
<pre><code class="lang-java"><span class="hljs-meta">@Configuration</span>
<span class="hljs-meta">@EnableWebSecurity</span>
<span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">SecurityConfig</span> <span class="hljs-keyword">extends</span> <span class="hljs-title">WebSecurityConfigurerAdapter</span> </span>{
    <span class="hljs-meta">@Autowired</span>
    <span class="hljs-keyword">private</span> UserDetailsService userDetailsService;

    <span class="hljs-meta">@Autowired</span>
    <span class="hljs-keyword">private</span> PasswordEncoder passwordEncoder;

    <span class="hljs-meta">@Override</span>
    <span class="hljs-function"><span class="hljs-keyword">protected</span> <span class="hljs-keyword">void</span> <span class="hljs-title">configure</span><span class="hljs-params">(HttpSecurity http)</span> <span class="hljs-keyword">throws</span> Exception </span>{
        http
            .authorizeRequests()
                .antMatchers(<span class="hljs-string">"/"</span>).permitAll()
                .antMatchers(<span class="hljs-string">"/admin/**"</span>).hasRole(<span class="hljs-string">"ADMIN"</span>)
                .anyRequest().authenticated()
                .and()
            .formLogin()
                .loginPage(<span class="hljs-string">"/login"</span>)
                .permitAll()
                .and()
            .logout()
                .permitAll();
    }

    <span class="hljs-meta">@Autowired</span>
    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">configureGlobal</span><span class="hljs-params">(AuthenticationManagerBuilder auth)</span> <span class="hljs-keyword">throws</span> Exception </span>{
        auth.userDetailsService(userDetailsService).passwordEncoder(passwordEncoder);
    }
}
</code></pre>
<p>In the above example, we are using the <code>http</code> object to define the security rules for our application. We are using the <code>authorizeRequests()</code> method to specify which resources in our application should be protected and which should be publicly accessible. In this case, we are allowing all requests to the root path (<code>/</code>) and only allowing requests from users with the "ADMIN" role to the <code>/admin</code> path. All other requests are required to be authenticated.</p>
<p>We are also configuring the form-based login and logout functionality using the <code>formLogin()</code> and <code>logout()</code> methods. In this case, we are using the default login page provided by Spring Security, but we can also specify a custom login page by providing a URL to the <code>loginPage()</code> method.</p>
<p>Finally, we are configuring the authentication manager to use our custom <code>UserDetailsService</code> and <code>PasswordEncoder</code> implementations.</p>
<h2 id="heading-authentication-and-authorization"><strong>Authentication and Authorization</strong></h2>
<p>One of the key features of Spring Security is its support for authentication and authorization. Authentication is the process of verifying a user's identity, while authorization is the process of determining what actions a user is allowed to perform.</p>
<p>Spring Security provides several built-in authentication mechanisms, such as form-based login, basic authentication, and token-based authentication. It also supports custom authentication providers, which allow developers to implement their authentication methods.</p>
<p>For example, in the configuration class above, we are using form-based login for authentication. However, we could also use basic authentication by configuring the <code>http</code> object as follows:</p>
<pre><code class="lang-java">http
    .authorizeRequests()
        .anyRequest().authenticated()
        .and()
    .httpBasic();
</code></pre>
<p>In this case, the user will be prompted to enter their credentials using a basic authentication dialog provided by the browser.</p>
<p>Once a user is authenticated, Spring Security uses the user's roles and authorities to determine what actions they are allowed to perform. Roles and authorities are used to define access-control rules, and they can be assigned to users in a variety of ways, such as using the <code>UserDetailsService</code> interface or by reading them from a database or LDAP server.</p>
<p>For example, in the configuration class above, we are using the <code>hasRole()</code> method to restrict access to the <code>/admin</code> path to users with the "ADMIN" role. We could also use the <code>hasAuthority()</code> method to restrict access based on a specific authority, such as <code>ROLE_ADMIN</code>.</p>
<h2 id="heading-securing-resources"><strong>Securing Resources</strong></h2>
<p>Spring Security can be used to secure a wide variety of resources, including web pages, RESTful web services, and even individual methods in a Java class.</p>
<p>For example, in the configuration class above, we are using the <code>authorizeRequests()</code> method to define security rules for web pages. However, we can also use the <code>antMatchers()</code> method to define rules for specific web services or methods.</p>
<p>Here is an example of how to secure a RESTful web service:</p>
<pre><code class="lang-java"><span class="hljs-meta">@Configuration</span>
<span class="hljs-meta">@EnableWebSecurity</span>
<span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">SecurityConfig</span> <span class="hljs-keyword">extends</span> <span class="hljs-title">WebSecurityConfigurerAdapter</span> </span>{
    <span class="hljs-comment">// ...</span>

    <span class="hljs-meta">@Override</span>
    <span class="hljs-function"><span class="hljs-keyword">protected</span> <span class="hljs-keyword">void</span> <span class="hljs-title">configure</span><span class="hljs-params">(HttpSecurity http)</span> <span class="hljs-keyword">throws</span> Exception </span>{
        http
            .authorizeRequests()
                .antMatchers(<span class="hljs-string">"/"</span>).permitAll()
                .antMatchers(<span class="hljs-string">"/admin/**"</span>).hasRole(<span class="hljs-string">"ADMIN"</span>)
                .antMatchers(HttpMethod.POST, <span class="hljs-string">"/api/**"</span>).hasRole(<span class="hljs-string">"USER"</span>)
                .anyRequest().authenticated()
                .and()
            <span class="hljs-comment">// ...</span>
    }
}
</code></pre>
<p>In this case, we are allowing all requests to the root path, allowing only users with the "ADMIN" role to access the <code>/admin</code> path, and allowing only users with the "USER" role to make POST requests to the <code>/api</code> path.</p>
<p>We can also use the <code>@PreAuthorize</code> and <code>@PostAuthorize</code> annotations to secure individual methods in a Java class. For example:</p>
<pre><code class="lang-java"><span class="hljs-meta">@Service</span>
<span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">MyService</span> </span>{
    <span class="hljs-meta">@PreAuthorize("hasRole('ADMIN')")</span>
    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">doAdminTask</span><span class="hljs-params">()</span> </span>{
        <span class="hljs-comment">// ...</span>
    }

    <span class="hljs-meta">@PostAuthorize("hasRole('USER')")</span>
    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">doUserTask</span><span class="hljs-params">()</span> </span>{
        <span class="hljs-comment">// ...</span>
    }
}
</code></pre>
<p>In this case, the <code>doAdminTask()</code> method can only be accessed by users with the "ADMIN" role, and the <code>doUserTask()</code> method can only be accessed by users with the "USER" role.</p>
<h2 id="heading-using-custom-roles-in-spring-security"><strong>Using Custom Roles in Spring Security</strong></h2>
<p>Spring Security supports the use of custom roles in addition to the built-in roles such as "ROLE_USER" and "ROLE_ADMIN". Custom roles can be used to define specific permissions and access controls for your application.</p>
<p>For example, let's say you have a music streaming application and you want to give premium users the ability to download songs. You can create a custom role called "ROLE_PREMIUM" and assign it to users who have a premium subscription. Then, you can use the <code>hasRole()</code> or <code>hasAuthority()</code> method to restrict access to the song download feature to users with the "ROLE_PREMIUM" role.</p>
<pre><code class="lang-java"><span class="hljs-meta">@Configuration</span>
<span class="hljs-meta">@EnableWebSecurity</span>
<span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">SecurityConfig</span> <span class="hljs-keyword">extends</span> <span class="hljs-title">WebSecurityConfigurerAdapter</span> </span>{
    <span class="hljs-comment">// ...</span>

    <span class="hljs-meta">@Override</span>
    <span class="hljs-function"><span class="hljs-keyword">protected</span> <span class="hljs-keyword">void</span> <span class="hljs-title">configure</span><span class="hljs-params">(HttpSecurity http)</span> <span class="hljs-keyword">throws</span> Exception </span>{
        http
            .authorizeRequests()
                .antMatchers(<span class="hljs-string">"/download/**"</span>).hasRole(<span class="hljs-string">"PREMIUM"</span>)
                .anyRequest().permitAll()
                .and()
            <span class="hljs-comment">// ...</span>
    }
}
</code></pre>
<p>In this case, only users with the "ROLE_PREMIUM" role will be able to access the "/download" path.</p>
<h2 id="heading-connecting-users-to-an-external-database"><strong>Connecting Users to an External Database</strong></h2>
<p>In most real-world applications, user data is stored in a database such as MySQL, PostgreSQL, or MongoDB. Spring Security provides a <code>UserDetailsService</code> interface that can be used to load user data from an external database.</p>
<p><code>UserDetailsService</code> is an interface with a single method, <code>loadUserByUsername(String username)</code>, that takes a username as an argument and returns a <code>UserDetails</code> object. <code>UserDetails</code> is a Spring Security interface that represents a user and their roles and authorities.</p>
<p>Here is an example of how to implement a <code>UserDetailsService</code> that loads user data from a MySQL database:</p>
<pre><code class="lang-java"><span class="hljs-meta">@Service</span>
<span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">MyUserDetailsService</span> <span class="hljs-keyword">implements</span> <span class="hljs-title">UserDetailsService</span> </span>{

    <span class="hljs-meta">@Autowired</span>
    <span class="hljs-keyword">private</span> UserRepository userRepository;

    <span class="hljs-meta">@Override</span>
    <span class="hljs-function"><span class="hljs-keyword">public</span> UserDetails <span class="hljs-title">loadUserByUsername</span><span class="hljs-params">(String username)</span> <span class="hljs-keyword">throws</span> UsernameNotFoundException </span>{
        User user = userRepository.findByUsername(username);
        <span class="hljs-keyword">if</span> (user == <span class="hljs-keyword">null</span>) {
            <span class="hljs-keyword">throw</span> <span class="hljs-keyword">new</span> UsernameNotFoundException(username);
        }
        <span class="hljs-keyword">return</span> <span class="hljs-keyword">new</span> MyUserPrincipal(user);
    }
}
</code></pre>
<p>In this example, we are using a <code>UserRepository</code> to load user data from a MySQL database. The <code>UserRepository</code> is an interface that extends <code>CrudRepository</code>, which is a Spring Data interface for working with databases.</p>
<p>Once you have implemented a <code>UserDetailsService</code>, you need to configure Spring Security to use it. You can do this by overriding the <code>configure(AuthenticationManagerBuilder auth)</code> method in the configuration class, like so:</p>
<pre><code class="lang-java"><span class="hljs-meta">@Configuration</span>
<span class="hljs-meta">@EnableWebSecurity</span>
<span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">SecurityConfig</span> <span class="hljs-keyword">extends</span> <span class="hljs-title">WebSecurityConfigurerAdapter</span> </span>{
    <span class="hljs-comment">// ...</span>

    <span class="hljs-meta">@Autowired</span>
    <span class="hljs-keyword">private</span> MyUserDetailsService userDetailsService;

    <span class="hljs-meta">@Override</span>
    <span class="hljs-function"><span class="hljs-keyword">protected</span> <span class="hljs-keyword">void</span> <span class="hljs-title">configure</span><span class="hljs-params">(AuthenticationManagerBuilder auth)</span> <span class="hljs-keyword">throws</span> Exception </span>{
        auth.userDetailsService(userDetailsService);
    }
}
</code></pre>
<p>With this configuration, Spring Security will use the <code>MyUserDetailsService</code> to load user data from the MySQL database.</p>
<p>It's important to note that when using an external database, you should also take care of security measures such as password encryption and securely storing the password. Spring Security provides built-in support for password encoding and provides several password encoders such as <code>BCryptPasswordEncoder</code>, <code>SHA-256PasswordEncoder</code>, etc.</p>
<p>Here is an example of how to configure Spring Security to use the <code>BCryptPasswordEncoder</code>:</p>
<pre><code class="lang-java"><span class="hljs-meta">@Configuration</span>
<span class="hljs-meta">@EnableWebSecurity</span>
<span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">SecurityConfig</span> <span class="hljs-keyword">extends</span> <span class="hljs-title">WebSecurityConfigurerAdapter</span> </span>{
    <span class="hljs-comment">// ...</span>

    <span class="hljs-meta">@Autowired</span>
    <span class="hljs-keyword">private</span> MyUserDetailsService userDetailsService;

    <span class="hljs-meta">@Bean</span>
    <span class="hljs-function"><span class="hljs-keyword">public</span> PasswordEncoder <span class="hljs-title">passwordEncoder</span><span class="hljs-params">()</span> </span>{
        <span class="hljs-keyword">return</span> <span class="hljs-keyword">new</span> BCryptPasswordEncoder();
    }

    <span class="hljs-meta">@Override</span>
    <span class="hljs-function"><span class="hljs-keyword">protected</span> <span class="hljs-keyword">void</span> <span class="hljs-title">configure</span><span class="hljs-params">(AuthenticationManagerBuilder auth)</span> <span class="hljs-keyword">throws</span> Exception </span>{
        auth
            .userDetailsService(userDetailsService)
            .passwordEncoder(passwordEncoder());
    }
}
</code></pre>
<p>In this example, we have defined a <code>passwordEncoder()</code> bean that returns a new <code>BCryptPasswordEncoder</code> and we have passed this password encoder to the <code>AuthenticationManagerBuilder</code>. This will ensure that all passwords are encoded using the <code>BCryptPasswordEncoder</code> before being compared with the stored passwords.</p>
<p>It's also worth mentioning that when working with an external database, you should also handle user's roles and authorities. It can be done by creating tables in the database to store roles and authorities of each user and then mapping them to <code>UserDetails</code> object.</p>
<h3 id="heading-managing-roles-and-authorities-in-spring-security-with-jpa-and-hibernate"><strong>Managing Roles and Authorities in Spring Security with JPA and Hibernate</strong></h3>
<p>When working with an external database, it's important to handle user's roles and authorities. Instead of writing raw SQL queries, we can use the power of JPA and Hibernate to handle the database operations. In this section, we will see how to implement this with JPA and Hibernate.</p>
<p>First, we need to create the entities that will represent the tables in the database. These entities will be used to map the tables in the database to Java objects. Here are examples of the entities that will represent the <code>users</code>, <code>authorities</code>, <code>roles</code>, and <code>user_roles</code> tables:</p>
<pre><code class="lang-java"><span class="hljs-meta">@Entity</span>
<span class="hljs-meta">@Table(name = "users")</span>
<span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">UserEntity</span> </span>{

    <span class="hljs-meta">@Id</span>
    <span class="hljs-meta">@GeneratedValue(strategy = GenerationType.AUTO)</span>
    <span class="hljs-keyword">private</span> Long id;

    <span class="hljs-meta">@Column(unique = true, nullable = false)</span>
    <span class="hljs-keyword">private</span> String username;

    <span class="hljs-meta">@Column(nullable = false)</span>
    <span class="hljs-keyword">private</span> String password;

    <span class="hljs-meta">@Column(nullable = false)</span>
    <span class="hljs-keyword">private</span> <span class="hljs-keyword">boolean</span> enabled;

    <span class="hljs-meta">@OneToMany(fetch = FetchType.LAZY, mappedBy = "user")</span>
    <span class="hljs-keyword">private</span> Set&lt;AuthorityEntity&gt; authorities;

    <span class="hljs-meta">@ManyToMany(fetch = FetchType.LAZY, cascade = CascadeType.ALL)</span>
    <span class="hljs-meta">@JoinTable(name = "user_roles", joinColumns = {
            @JoinColumn(name = "username", nullable = false, updatable = false) },
            inverseJoinColumns = { @JoinColumn(name = "role_id",
                    nullable = false, updatable = false) })</span>
    <span class="hljs-keyword">private</span> Set&lt;RoleEntity&gt; roles;
}

<span class="hljs-meta">@Entity</span>
<span class="hljs-meta">@Table(name = "authorities")</span>
<span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">AuthorityEntity</span> </span>{

    <span class="hljs-meta">@Id</span>
    <span class="hljs-meta">@GeneratedValue(strategy = GenerationType.AUTO)</span>
    <span class="hljs-keyword">private</span> Long id;

    <span class="hljs-meta">@ManyToOne(fetch = FetchType.LAZY)</span>
    <span class="hljs-meta">@JoinColumn(name = "username", nullable = false)</span>
    <span class="hljs-keyword">private</span> UserEntity user;

    <span class="hljs-meta">@Column(nullable = false)</span>
    <span class="hljs-keyword">private</span> String authority;
}

<span class="hljs-meta">@Entity</span>
<span class="hljs-meta">@Table(name = "roles")</span>
<span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">RoleEntity</span> </span>{

    <span class="hljs-meta">@Id</span>
    <span class="hljs-meta">@GeneratedValue(strategy = GenerationType.AUTO)</span>
    <span class="hljs-keyword">private</span> Long id;

    <span class="hljs-meta">@Column(unique = true, nullable = false)</span>
    <span class="hljs-keyword">private</span> String name;

    <span class="hljs-meta">@ManyToMany(fetch = FetchType.LAZY, mappedBy = "roles")</span>
    <span class="hljs-keyword">private</span> Set&lt;UserEntity&gt; users;
}
</code></pre>
<p>Once the entities are created, we need to create a <code>UserDetailsService</code> implementation that loads the user data from the database and maps it to the <code>UserDetails</code> object. Here is an example of a <code>UserDetailsService</code> implementation that loads the user data from the database using JPA and Hibernate:</p>
<pre><code class="lang-java"><span class="hljs-meta">@Service</span>
<span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">MyUserDetailsService</span> <span class="hljs-keyword">implements</span> <span class="hljs-title">UserDetailsService</span> </span>{

    <span class="hljs-meta">@Autowired</span>
    <span class="hljs-keyword">private</span> UserRepository userRepository;

    <span class="hljs-meta">@Override</span>
    <span class="hljs-function"><span class="hljs-keyword">public</span> UserDetails <span class="hljs-title">loadUserByUsername</span><span class="hljs-params">(String username)</span> <span class="hljs-keyword">throws</span> UsernameNotFoundException </span>{
        UserEntity userEntity = userRepository.findByUsername(username);
        <span class="hljs-keyword">if</span>(userEntity == <span class="hljs-keyword">null</span>) {
            <span class="hljs-keyword">throw</span> <span class="hljs-keyword">new</span> UsernameNotFoundException(<span class="hljs-string">"Invalid username or password."</span>);
        }
        <span class="hljs-keyword">return</span> <span class="hljs-keyword">new</span> org.springframework.security.core.userdetails.User(userEntity.getUsername(), userEntity.getPassword(), getAuthority(userEntity));
    }

    <span class="hljs-function"><span class="hljs-keyword">private</span> List&lt;SimpleGrantedAuthority&gt; <span class="hljs-title">getAuthority</span><span class="hljs-params">(UserEntity user)</span> </span>{
        <span class="hljs-keyword">return</span> user.getRoles().stream().map(role -&gt; <span class="hljs-keyword">new</span> SimpleGrantedAuthority(role.getName())).collect(Collectors.toList());
    }
}
</code></pre>
<p>As you can see, we are using a <code>UserRepository</code> interface that extends the <code>JpaRepository</code> interface. This interface will handle all the database operations related to the <code>UserEntity</code> class. The <code>findByUsername</code> method is used to find a user by its username, and the <code>getAuthority</code> method is used to map the user's roles to a <code>SimpleGrantedAuthority</code> object.</p>
<h1 id="heading-conclusion">Conclusion</h1>
<p>In conclusion, Spring Security is a powerful framework that provides a lot of features out of the box. In this article, we have covered some of the most important features of Spring Security and how to use them in a real-world application. We have discussed how to secure web applications with Spring Security and how to use authentication and authorization in Spring Security. We have also covered how to use custom roles and authorities in Spring Security and how to connect the users to an external database using JPA and Hibernate. With the help of these examples and explanations, you should now have a good understanding of how to use Spring Security in your web applications.</p>
]]></content:encoded></item><item><title><![CDATA[Spring Unit Testing with Mockito For Beginners]]></title><description><![CDATA[Spring Unit Testing with Mockito For Beginners
This tutorial is part of Springing into Action: A Spring Boot Journey from Novice to Pro Series, be sure to check it out for more related content!
Spring provides several powerful features for unit testi...]]></description><link>https://amrtechuniverse.com/spring-unit-testing-mockito-beginners</link><guid isPermaLink="true">https://amrtechuniverse.com/spring-unit-testing-mockito-beginners</guid><category><![CDATA[Springboot]]></category><category><![CDATA[Spring]]></category><category><![CDATA[mockito]]></category><category><![CDATA[Testing]]></category><category><![CDATA[Java]]></category><dc:creator><![CDATA[Amr Khaled]]></dc:creator><pubDate>Tue, 31 Jan 2023 11:00:39 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1675018197812/12c8b774-7a4c-40a1-9d3c-bbc52d5b5298.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<h1 id="heading-spring-unit-testing-with-mockito-for-beginners"><strong>Spring Unit Testing with Mockito For Beginners</strong></h1>
<p>This tutorial is part of <a target="_blank" href="https://amrtechuniverse.com/series/springboot-novice-to-pro"><strong>Springing into Action: A Spring Boot Journey from Novice to Pro</strong></a> Series, be sure to check it out for more related content!</p>
<p>Spring provides several powerful features for unit testing, including the ability to easily create mock objects and integrate them into the application context. In this article, we will explore how to use Mockito, a popular mocking framework, in conjunction with Spring to write effective unit tests.</p>
<h2 id="heading-setup"><strong>Setup</strong></h2>
<p>To get started, you will need to add the following dependency to your project's build file:</p>
<pre><code class="lang-xml"><span class="hljs-tag">&lt;<span class="hljs-name">dependency</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">groupId</span>&gt;</span>org.springframework.boot<span class="hljs-tag">&lt;/<span class="hljs-name">groupId</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">artifactId</span>&gt;</span>spring-starter-test<span class="hljs-tag">&lt;/<span class="hljs-name">artifactId</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">version</span>&gt;</span>2.4.0<span class="hljs-tag">&lt;/<span class="hljs-name">version</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">scope</span>&gt;</span>test<span class="hljs-tag">&lt;/<span class="hljs-name">scope</span>&gt;</span>
<span class="hljs-tag">&lt;/<span class="hljs-name">dependency</span>&gt;</span>
</code></pre>
<p>This <code>spring-starter-test</code> dependency includes a number of useful libraries for testing Spring-based applications, including JUnit, Hamcrest, and Mockito.</p>
<h1 id="heading-introduction-to-unit-testing"><strong>Introduction to Unit Testing</strong></h1>
<p>Unit testing is a software testing method in which individual units or components of a software application are tested in isolation from the rest of the system. The goal of unit testing is to validate that each unit of the software application is working as intended.</p>
<p>Unit tests are typically written by developers and are used to test the functionality of small, isolated components of the application such as methods or classes. Unit tests are automated and are run frequently during development to ensure that changes to the code do not break existing functionality.</p>
<h2 id="heading-benefits-of-unit-testing">Benefits of Unit Testing</h2>
<ul>
<li><p>Early detection of bugs and errors in the code.</p>
</li>
<li><p>Increased confidence in the code and the ability to make changes without fear of introducing new bugs.</p>
</li>
<li><p>Improved code quality and design.</p>
</li>
<li><p>Faster development times as developers can quickly and easily make changes to the code.</p>
</li>
</ul>
<p>Unit testing is just one type of testing and it's not enough to ensure that the whole application is working as expected. There are other types of testing as well, such as:</p>
<ul>
<li><p>Integration testing: testing how different units or components of the application work together.</p>
</li>
<li><p>Functional testing: testing the functionality of the application from the user's perspective.</p>
</li>
<li><p>Acceptance testing: testing the application to ensure that it meets the requirements of the end user.</p>
</li>
</ul>
<p>In general, unit testing is the foundation of software testing and provides a good starting point for more comprehensive testing. It's important to have a good unit testing strategy in place to ensure that the application is working as intended and to reduce the risk of bugs and errors.</p>
<p>Unit testing is an important part of software development and it's beneficial to have a good understanding of how to write and execute unit tests. Spring Boot provides a convenient way to write unit tests with its built-in support for testing, along with the tools such as JUnit, Mockito, and Spring Test.</p>
<h2 id="heading-understanding-mockito-framework"><strong>Understanding Mockito Framework</strong></h2>
<p>Mockito is a popular open-source testing framework for Java that allows developers to create mocks and stubs for their unit tests. It is designed to make it easy to write tests for your code by providing a simple, clean, and intuitive API. One of the key features of Mockito is its ability to create mocks and stubs of objects, which are used to simulate the behavior of real objects in a test environment.</p>
<h3 id="heading-mocks"><strong>Mocks</strong></h3>
<p>A mock object is a simulation of a real object that is used in place of the real object in a test environment. In Mockito, a mock object can be created using the <code>mock</code> method or the <code>@Mock</code> annotation. The <code>mock</code> method creates a mock object of a specific class, while the <code>@Mock</code> annotation creates a mock object of a field that is annotated with the <code>@Mock</code> annotation.</p>
<p>For example, we can create a mock of the <code>MyService</code> class like this:</p>
<pre><code class="lang-java">MyService myService = mock(MyService.class);
</code></pre>
<p>or</p>
<pre><code class="lang-java"><span class="hljs-meta">@Mock</span>
MyService myService;
</code></pre>
<h3 id="heading-spies"><strong>Spies</strong></h3>
<p>A spy object, on the other hand, is a special type of mock object that allows you to call the real methods of the object while still being able to specify the behavior of certain methods. In Mockito, a spy object can be created using the <code>spy</code> method or the <code>@Spy</code> annotation. The <code>spy</code> method creates a spy object of a specific class, while the <code>@Spy</code> annotation creates a spy object of a field that is annotated with the <code>@Spy</code> annotation.</p>
<p>For example, we can create a spy of the <code>MyService</code> class like this:</p>
<pre><code class="lang-java">MyService myService = spy(<span class="hljs-keyword">new</span> MyService());
</code></pre>
<p>or</p>
<pre><code class="lang-java"><span class="hljs-meta">@Spy</span>
MyService myService = <span class="hljs-keyword">new</span> MyService();
</code></pre>
<h3 id="heading-stubs"><strong>Stubs</strong></h3>
<p>A stub is an object that you can use to simulate the behavior of a real object in a test environment. In Mockito, a stub can be created using the <code>when</code> method. The <code>when</code> method is used to specify the behavior of a method for a specific input.</p>
<p>For example, we can use the <code>when</code> method to specify the behavior of the <code>isValid</code> method for a specific input:</p>
<pre><code class="lang-java">when(myService.isValid(<span class="hljs-string">"valid"</span>)).thenReturn(<span class="hljs-keyword">true</span>);
</code></pre>
<h3 id="heading-differences-between-mockbean-spybean-and-stub"><strong>Differences between</strong> <code>@MockBean</code>, <code>@SpyBean</code> and <code>@Stub</code></h3>
<p><code>@MockBean</code> is a Spring annotation that creates a mock of a bean and adds it to the Spring context. This means that the mock object will be used in place of the real object when it is injected into other beans.</p>
<p><code>@SpyBean</code> is also a Spring annotation that creates a spy of a bean and adds it to the Spring context. This means that the spy object will be used in place of the real object when it is injected into other beans, but it will still call the real methods of the object.</p>
<p><code>@Stub</code> is not a Spring annotation it is a term used to describe the use of the <code>when</code> method from the Mockito framework, which is used to specify the behavior of a method for a specific input.</p>
<p>In general, <code>@MockBean</code> and <code>@SpyBean</code> are used to create mocks and spies of objects that are used in the Spring context, while the <code>when</code> method is used to create stubs of methods for specific inputs. It's important to note that the usage of these annotations and methods depend on the specific needs of your test case and the behavior you want to simulate.</p>
<p>For example, if you want to test the behavior of a service class that makes a call to a repository class, you might use a <code>@MockBean</code> annotation to create a mock of the repository class so that you can control its behavior in the test. On the other hand, if you want to test the behavior of a service class that makes a call to a external API, you might use the <code>when</code> method to create a stub of the API call and control its behavior in the test.</p>
<p>In summary, the key difference between using <code>@MockBean</code>, <code>@SpyBean</code> and <code>when</code> method is that <code>@MockBean</code> and <code>@SpyBean</code> are used to create mocks and spies of objects that are used in the Spring context, while the <code>when</code> method is used to create stubs of methods for specific inputs.</p>
<h1 id="heading-configuration-class-for-springboottest"><strong>Configuration Class for SpringBootTest</strong></h1>
<p>In addition to the annotations and methods discussed above, Spring also provides a way to configure the test context through the use of configuration classes. These classes can be used to specify which beans should be loaded for the test and which should be excluded.</p>
<p>For example, the following configuration class can be used to only load the beans that are needed for the test and exclude the others:</p>
<pre><code class="lang-java"><span class="hljs-meta">@Configuration</span>
<span class="hljs-meta">@Import({ Service.class, Repository.class })</span>
<span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">TestConfig</span> </span>{

}
</code></pre>
<p>This configuration class can then be used in the test class as follows:</p>
<pre><code class="lang-java"><span class="hljs-meta">@RunWith(SpringRunner.class)</span>
<span class="hljs-meta">@SpringBootTest(classes = TestConfig.class)</span>
<span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">MyTest</span> </span>{
    ...
}
</code></pre>
<p>This way we can include only the classes that are needed for the test and exclude the others. This can be especially useful when we have a large application and we only want to test a specific part of it.</p>
<p>It is also possible to specify the configuration class while using <code>@DataJpaTest</code>, <code>@WebMvcTest</code>, <code>@JsonTest</code> and other annotations that provide a slice of the context.</p>
<pre><code class="lang-java"><span class="hljs-meta">@WebMvcTest(controllers = MyController.class, config = TestConfig.class)</span>
</code></pre>
<p>This is particularly useful when you want to test only specific layers of your application, such as the web layer or the data access layer.</p>
<h2 id="heading-spring-starter-test-usage"><strong>Spring Starter Test Usage</strong></h2>
<p>One of the most powerful features of Spring for unit testing is the ability to easily create mock objects and integrate them into the application context. We can use the <code>@MockBean</code> annotation to create a mock of a bean and automatically add it to the application context. For example:</p>
<pre><code class="lang-java"><span class="hljs-meta">@MockBean</span>
<span class="hljs-keyword">private</span> MyService myService;
</code></pre>
<p>In this example, a mock of the <code>MyService</code> bean is created and automatically added to the application context. We can then use this mock to write test cases and verify that the correct methods are called with the correct arguments.</p>
<p>We can also use the <code>@SpyBean</code> annotation to create a spy of a bean instead of a mock. Spies are useful when we want to test the behavior of a bean while still calling the real methods.</p>
<p>The <code>@TestExecutionListeners</code> annotation can be used to specify one or more test execution listeners that will be used for the test class. The <code>DependencyInjectionTestExecutionListener</code> is one of the built-in listeners provided by Spring and it can be used to control the order of test methods.</p>
<p>For example, we can use the <code>@Dependencies</code> annotation to specify the order in which methods should be executed:</p>
<pre><code class="lang-java"><span class="hljs-meta">@TestExecutionListeners(DependencyInjectionTestExecutionListener.class)</span>
<span class="hljs-meta">@Dependencies({ TestMethod1.class, TestMethod2.class })</span>
<span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Test</span> </span>{
    <span class="hljs-comment">// test methods here</span>

    <span class="hljs-meta">@Test</span>
    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">testMethod1</span><span class="hljs-params">()</span> </span>{
        <span class="hljs-comment">// test code here</span>
    }

    <span class="hljs-meta">@Test</span>
    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">testMethod2</span><span class="hljs-params">()</span> </span>{
        <span class="hljs-comment">// test code here</span>
    }
}
</code></pre>
<p>In the example above, we are using the <code>@TestExecutionListeners</code> annotation to specify that the <code>DependencyInjectionTestExecutionListener</code> will be used for the test class. This listener can be used to control the order of test methods, for example by specifying the <code>@Dependencies</code> annotation.</p>
<p>To test with the context re-usage, we can use the <code>@DirtiesContext</code> annotation. This annotation can be used to indicate that a test method has dirtied the context, and that the context should be rebuilt before the next test method is executed. For example:</p>
<pre><code class="lang-java"><span class="hljs-meta">@Test</span>
<span class="hljs-meta">@DirtiesContext</span>
<span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">testMethod</span><span class="hljs-params">()</span> </span>{
    <span class="hljs-comment">// test code here</span>
}
</code></pre>
<p>In this example, the context will be rebuilt before the next test method is executed.</p>
<p>There are also ways to control the order of test classes and methods, for example using the <code>@TestPropertySource</code> annotation. This annotation can be used to specify properties that should be used for a test class or method. For example:</p>
<pre><code class="lang-java"><span class="hljs-meta">@TestPropertySource(properties = { "property1=value1", "property2=value2" })</span>
<span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Test</span> </span>{
    <span class="hljs-comment">// test methods here</span>
}
</code></pre>
<p>In this example, the properties <code>property1</code> and <code>property2</code> will be set to <code>value1</code> and <code>value2</code> respectively for all the test methods in this class.</p>
<p>Another way to control the order of test classes and methods is by using the <code>@TestMethodOrder</code> annotation. This annotation can be used to specify the order in which test methods should be executed. For example:</p>
<pre><code class="lang-java"><span class="hljs-meta">@TestMethodOrder(OrderAnnotation.class)</span>
<span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Test</span> </span>{
    <span class="hljs-comment">// test methods here</span>

    <span class="hljs-meta">@Order(1)</span>
    <span class="hljs-meta">@Test</span>
    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">testMethod1</span><span class="hljs-params">()</span> </span>{
        <span class="hljs-comment">// test code here</span>
    }

    <span class="hljs-meta">@Order(2)</span>
    <span class="hljs-meta">@Test</span>
    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">testMethod2</span><span class="hljs-params">()</span> </span>{
        <span class="hljs-comment">// test code here</span>
    }
}
</code></pre>
<p>In this example, the <code>testMethod1</code> will be executed before the <code>testMethod2</code> because it is annotated with <code>@Order(1)</code> and <code>testMethod2</code> is annotated with <code>@Order(2)</code>.</p>
<h2 id="heading-code-examples"><strong>Code Examples</strong></h2>
<p>Here is an example of a simple unit test using Mockito and Spring:</p>
<pre><code class="lang-java"><span class="hljs-meta">@RunWith(SpringRunner.class)</span>
<span class="hljs-meta">@SpringBootTest</span>
<span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">MyServiceTest</span> </span>{

    <span class="hljs-meta">@MockBean</span>
    <span class="hljs-keyword">private</span> MyRepository repository;

    <span class="hljs-meta">@Autowired</span>
    <span class="hljs-keyword">private</span> MyService service;

    <span class="hljs-meta">@Test</span>
    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">testGetData</span><span class="hljs-params">()</span> </span>{
        when(repository.findById(<span class="hljs-number">1L</span>)).thenReturn(<span class="hljs-keyword">new</span> MyData(<span class="hljs-number">1L</span>, <span class="hljs-string">"Test Data"</span>));
        MyData data = service.getData(<span class="hljs-number">1L</span>);
        assertEquals(<span class="hljs-number">1L</span>, data.getId());
        assertEquals(<span class="hljs-string">"Test Data"</span>, data.getValue());
        verify(repository).findById(<span class="hljs-number">1L</span>);
    }
}
</code></pre>
<p>In this example, we are using the <code>@MockBean</code> annotation to create a mock of the <code>MyRepository</code> bean and <code>@Autowired</code> annotation to inject the <code>MyService</code> bean into the test class. We are then using the <code>when</code> method from Mockito to specify the behavior of the mock repository and using the <code>verify</code> method to check that the <code>findById</code> method is called with the correct argument.</p>
<p>Here is an example of a unit test using <code>@SpyBean</code> and <code>@DirtiesContext</code>:</p>
<pre><code class="lang-java"><span class="hljs-meta">@RunWith(SpringRunner.class)</span>
<span class="hljs-meta">@SpringBootTest</span>
<span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">MyServiceTest</span> </span>{

    <span class="hljs-meta">@SpyBean</span>
    <span class="hljs-keyword">private</span> MyService service;

    <span class="hljs-meta">@Test</span>
    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">testDoSomething</span><span class="hljs-params">()</span> </span>{
        doReturn(<span class="hljs-keyword">true</span>).when(service).isValid();
        service.doSomething();
        verify(service).isValid();
        verify(service).saveData();
    }

    <span class="hljs-meta">@Test</span>
    <span class="hljs-meta">@DirtiesContext</span>
    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">testDoSomethingElse</span><span class="hljs-params">()</span> </span>{
        doReturn(<span class="hljs-keyword">false</span>).when(service).isValid();
        service.doSomething();
        verify(service, never()).saveData();
    }
}
</code></pre>
<p>In this example, we are using the <code>@SpyBean</code> annotation to create a spy of the <code>MyService</code> bean, which allows us to test the behavior of the bean while still calling the real methods. In the <code>testDoSomething</code> method, we are using the <code>doReturn</code> method from Mockito to specify the behavior of the <code>isValid</code> method and then verifying that the <code>saveData</code> method is called. In the <code>testDoSomethingElse</code> method, we are also using the <code>doReturn</code> method to specify the behavior of the <code>isValid</code> method, but this time we are expecting the <code>saveData</code> method to not be called. We are also using the <code>@DirtiesContext</code> annotation on this method to indicate that the context should be dirtied after this test method is executed. This means that any changes made to the context during this test method will not affect the other test methods.</p>
<h1 id="heading-mocking-static-methods-in-classes-for-tests"><strong>Mocking Static Methods in Classes for Tests</strong></h1>
<p>In some cases, we may need to test a class that has static methods or a static class itself. Mocking static methods can be a bit tricky as mockito does not support mocking of static methods by default, but it can be done by using the <code>Mockito.mock()</code> with <code>Mockito.spy()</code> .</p>
<p>Here is an example of how to use <code>Mockito.spy()</code> to mock a static method:</p>
<pre><code class="lang-java"><span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">MyTest</span> </span>{
    <span class="hljs-meta">@Test</span>
    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">testStaticMethod</span><span class="hljs-params">()</span> </span>{
        MyStaticClass spy = Mockito.spy(MyStaticClass.class);
        Mockito.doReturn(<span class="hljs-string">"mocked result"</span>).when(spy).staticMethod();
        String result = spy.staticMethod();
        assertEquals(<span class="hljs-string">"mocked result"</span>, result);
    }
}
</code></pre>
<p>In this example, we use the <code>Mockito.spy()</code> method to create a spy of the static class, and the <code>Mockito.doReturn()</code> method is used to specify the behavior of the static method.</p>
<p>It's worth noting that using <code>Mockito.spy()</code> is not recommended in some cases as it's not always recommended to test static methods and classes because in some cases it might be better to refactor the code and make it testable by using dependency injection and interfaces.</p>
<h1 id="heading-parallel-execution-of-tests"><strong>Parallel Execution of Tests</strong></h1>
<p>Parallel execution of tests is a way to speed up the testing process by running multiple tests at the same time. This can be achieved in Spring Boot by configuring the properties file and specifying the number of threads to use for running tests.</p>
<h2 id="heading-parallel-execution-within-the-same-class"><strong>Parallel Execution within the Same Class</strong></h2>
<p>To run tests in parallel within the same class, we can use the <code>@Test(threadPoolSize = X, invocationCount = Y)</code> annotation. <code>threadPoolSize</code> represents the number of threads to use for running the tests, and <code>invocationCount</code> represents the number of times the test method should be invoked. For example, if we have a test class with 4 test methods and we want to run them in parallel using 2 threads, the configuration would look like this:</p>
<pre><code class="lang-java"><span class="hljs-meta">@Test(threadPoolSize = 2, invocationCount = 4)</span>
<span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">testMethod</span><span class="hljs-params">()</span> </span>{
    <span class="hljs-comment">// test logic here</span>
}
</code></pre>
<h2 id="heading-parallel-execution-across-classes"><strong>Parallel Execution Across Classes</strong></h2>
<p>To run tests in parallel across different classes, we can use the <code>@Test(threadPoolSize = X)</code> annotation at the class level. This will run all the test methods within the class in parallel using the specified number of threads. For example, if we have 2 test classes with 4 test methods each and we want to run them in parallel using 2 threads, the configuration would look like this:</p>
<pre><code class="lang-java"><span class="hljs-meta">@Test(threadPoolSize = 2)</span>
<span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">TestClass1</span> </span>{
    <span class="hljs-meta">@Test</span>
    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">testMethod1</span><span class="hljs-params">()</span> </span>{
        <span class="hljs-comment">// test logic here</span>
    }
    <span class="hljs-meta">@Test</span>
    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">testMethod2</span><span class="hljs-params">()</span> </span>{
        <span class="hljs-comment">// test logic here</span>
    }
    <span class="hljs-comment">// additional test methods</span>
}

<span class="hljs-meta">@Test(threadPoolSize = 2)</span>
<span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">TestClass2</span> </span>{
    <span class="hljs-meta">@Test</span>
    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">testMethod1</span><span class="hljs-params">()</span> </span>{
        <span class="hljs-comment">// test logic here</span>
    }
    <span class="hljs-meta">@Test</span>
    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">testMethod2</span><span class="hljs-params">()</span> </span>{
        <span class="hljs-comment">// test logic here</span>
    }
    <span class="hljs-comment">// additional test methods</span>
}
</code></pre>
<p>You can also use the <code>spring.test.parallel.execution.enabled</code> and <code>spring.test.parallel.execution.strategy</code> in the <code>application.properties</code> file to configure the parallel execution.</p>
<pre><code class="lang-java">spring.test.parallel.execution.enabled=<span class="hljs-keyword">true</span>
spring.test.parallel.execution.strategy=classes
</code></pre>
<p>The <code>strategy</code> property can take values of <code>classes</code> and <code>methods</code>. <code>classes</code> runs all the test classes in parallel and <code>methods</code> runs all the test methods within a class in parallel.</p>
<p>It's worth noting that parallel execution may cause some test methods to fail due to the shared state or unexpected order of test execution. Therefore, it's important to make sure that your test methods are independent and not dependent on the execution order.</p>
<h2 id="heading-conclusion"><strong>Conclusion</strong></h2>
<p>In conclusion, Spring unit testing with Mockito is a powerful combination for testing Spring applications. We have covered various features and annotations such as <code>@MockBean</code>, <code>@SpyBean</code>, and <code>@TestExecutionListeners</code> that allow us to fine-tune our tests and ensure that they are accurate and reliable. Additionally, we discussed the differences between mock, spy, and stub annotations and the usage scenarios for each.</p>
<p>Moreover, we also covered the configuration class for SpringBootTest and how to specify only some classes to run for testing and not the whole context, this is useful when we want to test a specific set of classes and not all the classes in the application. Also, we discussed how to mock static methods in classes for tests and testing static classes with code examples.</p>
<p>Finally, we discussed the importance of unit testing and its benefits, including the different types of testing such as unit tests and integration tests. Additionally, we covered the parallel execution of tests in the same class or parallel execution of tests across classes using the properties file in SpringBootTests and the differences and configurations needed with examples in code and execution time.</p>
<p>In summary, Spring unit testing with Mockito is a powerful tool for ensuring the reliability and accuracy of your Spring applications. With the various features and annotations provided by Spring and Mockito, you can fine-tune your tests to suit your specific needs and ensure that your application is working as expected.</p>
]]></content:encoded></item><item><title><![CDATA[Mastering Spring Boot Actuator: Monitoring and Managing Your Applications]]></title><description><![CDATA[This tutorial is part of Springing into Action: A Spring Boot Journey from Novice to Pro Series, be sure to check it out for more related content!
Spring Boot Actuator is a powerful tool for monitoring and managing your Spring Boot applications at ru...]]></description><link>https://amrtechuniverse.com/mastering-spring-boot-actuator-monitoring-and-managing-your-applications</link><guid isPermaLink="true">https://amrtechuniverse.com/mastering-spring-boot-actuator-monitoring-and-managing-your-applications</guid><category><![CDATA[Actuator]]></category><category><![CDATA[Springboot]]></category><category><![CDATA[Spring]]></category><category><![CDATA[Spring framework]]></category><category><![CDATA[Java]]></category><dc:creator><![CDATA[Amr Khaled]]></dc:creator><pubDate>Mon, 30 Jan 2023 15:00:39 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1675000935104/30dfcc92-84e6-43d3-9fcd-99d4073f249c.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>This tutorial is part of <a target="_blank" href="https://amrtechuniverse.com/series/springboot-novice-to-pro"><strong>Springing into Action: A Spring Boot Journey from Novice to Pro</strong></a> Series, be sure to check it out for more related content!</p>
<p>Spring Boot Actuator is a powerful tool for monitoring and managing your Spring Boot applications at runtime. It provides a wide range of information about the application and its environment; and allows for the management of the application. In this article, we will explore the features of Spring Boot Actuator and how to add it to your project, usage and code examples to help you understand how it can improve the reliability and maintainability of your Spring Boot applications.</p>
<h2 id="heading-what-is-spring-boot-actuator"><strong>What is Spring Boot Actuator?</strong></h2>
<p>Spring Boot Actuator is a sub-project of Spring Boot that provides advanced monitoring and management capabilities for Spring Boot applications. It provides a set of endpoints that allow you to monitor and manage your application at runtime. These endpoints provide information about the application, such as its health, metrics, and configuration, as well as allow you to perform operations on the application, such as refreshing its configuration or shutting it down.</p>
<h2 id="heading-adding-spring-boot-actuator-to-your-project"><strong>Adding Spring Boot Actuator to Your Project</strong></h2>
<p>Adding Spring Boot Actuator to your project is easy. All you need to do is add the <code>spring-boot-starter-actuator</code> dependency on your project's <code>pom.xml</code> file.</p>
<pre><code class="lang-xml"><span class="hljs-tag">&lt;<span class="hljs-name">dependency</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">groupId</span>&gt;</span>org.springframework.boot<span class="hljs-tag">&lt;/<span class="hljs-name">groupId</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">artifactId</span>&gt;</span>spring-boot-starter-actuator<span class="hljs-tag">&lt;/<span class="hljs-name">artifactId</span>&gt;</span>
<span class="hljs-tag">&lt;/<span class="hljs-name">dependency</span>&gt;</span>
</code></pre>
<p>Once you've added the dependency, you can start using Actuator's endpoints by visiting <a target="_blank" href="http://localhost:8080/actuator"><code>http://localhost:8080/actuator</code></a> in your browser.</p>
<h2 id="heading-available-endpoints"><strong>Available Endpoints</strong></h2>
<p>Spring Boot Actuator provides a wide range of endpoints that allow you to monitor and manage your application at runtime. Here are some of the most commonly used endpoints:</p>
<h3 id="heading-health-endpoint"><strong>Health Endpoint</strong></h3>
<p>The <code>health</code> endpoint provides information about the health of your application. It returns a JSON object that contains the status of the application, as well as any additional information that may be useful for monitoring the application's health. By default, the <code>health</code> endpoint returns only the status of the application, but you can configure it to return additional information by implementing the <code>HealthIndicator</code> interface.</p>
<p>For example, you can create a custom <code>HealthIndicator</code> that returns the current time:</p>
<pre><code class="lang-java"><span class="hljs-meta">@Component</span>
<span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">TimeHealthIndicator</span> <span class="hljs-keyword">implements</span> <span class="hljs-title">HealthIndicator</span> </span>{

    <span class="hljs-meta">@Override</span>
    <span class="hljs-function"><span class="hljs-keyword">public</span> Health <span class="hljs-title">health</span><span class="hljs-params">()</span> </span>{
        String currentTime = LocalDateTime.now().toString();
        <span class="hljs-keyword">return</span> Health.up().withDetail(<span class="hljs-string">"time"</span>, currentTime).build();
    }
}
</code></pre>
<h3 id="heading-metrics-endpoint"><strong>Metrics Endpoint</strong></h3>
<p>The <code>metrics</code> endpoint provides information about the performance of your application. It returns a JSON object that contains various metrics, such as the number of requests per second, the average response time, and the memory usage of the application. You can configure which metrics are exposed by Actuator by using the <code>management.metrics.export</code> property.</p>
<h3 id="heading-info-endpoint"><strong>Info Endpoint</strong></h3>
<p>The <code>info</code> endpoint provides information about the application, such as its version and build time. You can configure the information that is exposed by Actuator by using the <code>info</code> property in the <a target="_blank" href="http://application.properties"><code>application.properties</code></a> file. For example, you can add the following properties to the file:</p>
<pre><code class="lang-java">info.app.name=My Application
info.app.version=<span class="hljs-number">1.0</span>
</code></pre>
<h3 id="heading-configuration-endpoint"><strong>Configuration Endpoint</strong></h3>
<p>The <code>configprops</code> endpoint provides information about the configuration of your application. It returns a JSON object that contains all the properties defined in the <a target="_blank" href="http://application.properties"><code>application.properties</code></a> or <code>application.yml</code> file, as well as any other configuration properties that are defined by the application's dependencies. This can be useful for troubleshooting configuration issues and for understanding the configuration of your application at runtime.</p>
<h3 id="heading-beans-endpoint"><strong>Beans Endpoint</strong></h3>
<p>The <code>beans</code> endpoint provides information about the beans that are defined in your application's context. It returns a JSON object that contains all the beans that are defined, as well as information about their scope, type, and dependencies. This can be useful for understanding how your application is constructed and for troubleshooting issues related to bean initialization.</p>
<h3 id="heading-threads-endpoint"><strong>Threads Endpoint</strong></h3>
<p>The <code>threaddump</code> endpoint provides information about the threads that are currently running in your application. It returns a JSON object that contains information about each thread, such as its name, state, and call stack. This can be useful for troubleshooting performance issues and for understanding how your application is utilizing resources.</p>
<h3 id="heading-shutdown-endpoint"><strong>Shutdown Endpoint</strong></h3>
<p>The <code>shutdown</code> endpoint allows you to safely shut down your application. It is disabled by default, but you can enable it by setting the <code>management.endpoint.shutdown.enabled</code> property to <code>true</code>. Once it is enabled, you can send a <code>POST</code> request to the <code>shutdown</code> endpoint to shut down the application. This can be useful for performing maintenance tasks or for shutting down the application in response to an error.</p>
<h2 id="heading-extending-actuator-endpoints"><strong>Extending Actuator Endpoints</strong></h2>
<p>Actuator provides a wide range of endpoints out of the box, but you may find that you need to add your custom endpoints to your application. Spring Boot Actuator makes it easy to extend the existing endpoints or to define your custom endpoints.</p>
<h3 id="heading-extending-existing-endpoints"><strong>Extending Existing Endpoints</strong></h3>
<p>You can extend existing endpoints by creating a new class that implements the appropriate <code>Endpoint</code> interface. For example, if you want to add additional information to the <code>health</code> endpoint, you can create a new class that implements the <code>HealthEndpoint</code> interface.</p>
<pre><code class="lang-java"><span class="hljs-meta">@Component</span>
<span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">CustomHealthEndpoint</span> <span class="hljs-keyword">implements</span> <span class="hljs-title">HealthEndpoint</span> </span>{

    <span class="hljs-keyword">private</span> <span class="hljs-keyword">final</span> HealthEndpoint delegate;

    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-title">CustomHealthEndpoint</span><span class="hljs-params">(HealthEndpoint delegate)</span> </span>{
        <span class="hljs-keyword">this</span>.delegate = delegate;
    }

    <span class="hljs-meta">@Override</span>
    <span class="hljs-function"><span class="hljs-keyword">public</span> Health <span class="hljs-title">health</span><span class="hljs-params">()</span> </span>{
        Health health = delegate.health();
        <span class="hljs-comment">// Add custom information to the health object</span>
        <span class="hljs-keyword">return</span> health;
    }
}
</code></pre>
<p>You can also use <code>@EndpointExtension</code> to extend existing endpoints. This annotation is used to indicate that a bean should be used as an extension of an existing endpoint.</p>
<pre><code class="lang-java"><span class="hljs-meta">@Component</span>
<span class="hljs-meta">@EndpointExtension(endpoint = HealthEndpoint.class)</span>
<span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">CustomHealthEndpointExtension</span> </span>{
    <span class="hljs-comment">// Add custom information to the health object</span>
}
</code></pre>
<h3 id="heading-defining-custom-endpoints"><strong>Defining Custom Endpoints</strong></h3>
<p>You can define your custom endpoints by creating a new class that implements the <code>Endpoint</code> interface. For example, you can create a new endpoint that returns information about the current time:</p>
<pre><code class="lang-java"><span class="hljs-meta">@Component</span>
<span class="hljs-meta">@Endpoint(id = "time")</span>
<span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">TimeEndpoint</span> <span class="hljs-keyword">implements</span> <span class="hljs-title">Endpoint</span>&lt;<span class="hljs-title">String</span>&gt; </span>{

    <span class="hljs-meta">@Override</span>
    <span class="hljs-function"><span class="hljs-keyword">public</span> String <span class="hljs-title">invoke</span><span class="hljs-params">()</span> </span>{
        <span class="hljs-keyword">return</span> LocalDateTime.now().toString();
    }

    <span class="hljs-meta">@Override</span>
    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">boolean</span> <span class="hljs-title">isEnabled</span><span class="hljs-params">()</span> </span>{
        <span class="hljs-keyword">return</span> <span class="hljs-keyword">true</span>;
    }

    <span class="hljs-meta">@Override</span>
    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">boolean</span> <span class="hljs-title">isSensitive</span><span class="hljs-params">()</span> </span>{
        <span class="hljs-keyword">return</span> <span class="hljs-keyword">false</span>;
    }
}
</code></pre>
<p>You can also use <code>@Endpoint</code> to define custom endpoints. This annotation is used to indicate that a bean should be registered as a new endpoint.</p>
<pre><code class="lang-java"><span class="hljs-meta">@Component</span>
<span class="hljs-meta">@Endpoint(id = "custom")</span>
<span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">CustomEndpoint</span> </span>{

    <span class="hljs-meta">@ReadOperation</span>
    <span class="hljs-function"><span class="hljs-keyword">public</span> String <span class="hljs-title">customEndpoint</span><span class="hljs-params">()</span> </span>{
        <span class="hljs-keyword">return</span> <span class="hljs-string">"Hello from custom endpoint"</span>;
    }
}
</code></pre>
<p>Once you have defined your custom endpoint, you can access it by sending a <code>GET</code> request to the <code>/actuator/{id}</code> endpoint, where <code>{id}</code> is the ID of your custom endpoint.</p>
<p>By extending and defining custom endpoints, you can add new functionality to your Actuator endpoints and customize them to suit the needs of your application.</p>
<h2 id="heading-conclusion"><strong>Conclusion</strong></h2>
<p>Spring Boot Actuator is a powerful tool for monitoring and managing your Spring Boot applications at runtime. It provides a wide range of endpoints that allow you to monitor and manage your application, from its health and performance to its configuration and resources. Actuator also allows you to extend and define custom endpoints to suit the needs of your application. By adding Actuator to your project and understanding its capabilities, you can improve the reliability and maintainability of your Spring Boot applications.</p>
]]></content:encoded></item><item><title><![CDATA[Netflix OSS: Building Robust and Scalable Microservices with Spring Boot]]></title><description><![CDATA[This tutorial is part of Springing into Action: A Spring Boot Journey from Novice to Pro Series, be sure to check it out for more related content!
Microservices architecture has become increasingly popular in recent years as a way to build scalable a...]]></description><link>https://amrtechuniverse.com/netflix-oss-building-robust-and-scalable-microservices-with-spring-boot</link><guid isPermaLink="true">https://amrtechuniverse.com/netflix-oss-building-robust-and-scalable-microservices-with-spring-boot</guid><category><![CDATA[Springboot]]></category><category><![CDATA[Spring]]></category><category><![CDATA[Java]]></category><category><![CDATA[Microservices]]></category><category><![CDATA[netflix-oss]]></category><dc:creator><![CDATA[Amr Khaled]]></dc:creator><pubDate>Mon, 30 Jan 2023 11:00:38 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1674999119258/25fded3f-d567-40d9-9312-6b50752529dc.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>This tutorial is part of <a target="_blank" href="https://amrtechuniverse.com/series/springboot-novice-to-pro"><strong>Springing into Action: A Spring Boot Journey from Novice to Pro</strong></a> Series, be sure to check it out for more related content!</p>
<p>Microservices architecture has become increasingly popular in recent years as a way to build scalable and resilient applications. However, building and maintaining a microservices-based system can be challenging, especially when it comes to service discovery, load balancing, and fault tolerance. Netflix OSS (Open Source Software) is a set of tools and frameworks that can help to address these challenges and make it easier to build and maintain a microservices-based system. In this article, we will take a look at how to integrate Netflix OSS with a Spring Boot application to improve its reliability, scalability, and performance.</p>
<h2 id="heading-eureka"><strong>Eureka</strong></h2>
<p>Eureka is a service discovery and registry tool. It allows services to register themselves and discover other services in the system. In a microservices-based system, services often need to call other services to perform their tasks. Eureka makes it easy for services to find and call other services by maintaining a registry of all the services in the system.</p>
<p>To integrate Eureka with our Spring Boot application, we first need to add the Spring Cloud Netflix Eureka dependency to our project.</p>
<pre><code class="lang-xml"><span class="hljs-tag">&lt;<span class="hljs-name">dependency</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">groupId</span>&gt;</span>org.springframework.cloud<span class="hljs-tag">&lt;/<span class="hljs-name">groupId</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">artifactId</span>&gt;</span>spring-cloud-starter-netflix-eureka-client<span class="hljs-tag">&lt;/<span class="hljs-name">artifactId</span>&gt;</span>
<span class="hljs-tag">&lt;/<span class="hljs-name">dependency</span>&gt;</span>
</code></pre>
<p>Next, we need to enable Eureka in our service by adding the <code>@EnableEurekaClient</code> annotation to our main class.</p>
<pre><code class="lang-java"><span class="hljs-meta">@SpringBootApplication</span>
<span class="hljs-meta">@EnableEurekaClient</span>
<span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">MyApplication</span> </span>{

    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> <span class="hljs-keyword">void</span> <span class="hljs-title">main</span><span class="hljs-params">(String[] args)</span> </span>{
        SpringApplication.run(MyApplication.class, args);
    }
}
</code></pre>
<p>We also need to configure the Eureka server URL in our application properties.</p>
<pre><code class="lang-xml">eureka.client.service-url.default-zone=http://localhost:8761/eureka/
</code></pre>
<p>With these configurations in place, our service will register itself with the Eureka server and be discoverable by other services in the system.</p>
<h2 id="heading-ribbon"><strong>Ribbon</strong></h2>
<p>Ribbon is a client-side load balancer. It allows a service to distribute load among multiple instances of a dependent service. In a microservices-based system, it is common for a service to have multiple instances to handle increased traffic. Ribbon makes it easy for a service to distribute load among these instances, improving the system's scalability.</p>
<p>To integrate Ribbon with our Spring Boot application, we first need to add the Spring Cloud Netflix Ribbon dependency to our project.</p>
<pre><code class="lang-xml"><span class="hljs-tag">&lt;<span class="hljs-name">dependency</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">groupId</span>&gt;</span>org.springframework.cloud<span class="hljs-tag">&lt;/<span class="hljs-name">groupId</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">artifactId</span>&gt;</span>spring-cloud-starter-netflix-ribbon<span class="hljs-tag">&lt;/<span class="hljs-name">artifactId</span>&gt;</span>
<span class="hljs-tag">&lt;/<span class="hljs-name">dependency</span>&gt;</span>
</code></pre>
<p>Next, we need to use the <code>RestTemplate</code> class with <code>@LoadBalanced</code> annotation to make a call to dependent services.</p>
<pre><code class="lang-java"><span class="hljs-meta">@Autowired</span>
<span class="hljs-meta">@LoadBalanced</span>
<span class="hljs-keyword">private</span> RestTemplate restTemplate;

<span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">callDependentService</span><span class="hljs-params">()</span> </span>{
    restTemplate.getForObject(<span class="hljs-string">"http://my-service/endpoint"</span>, String.class);
}
</code></pre>
<p>With these configurations in place, Ribbon will automatically handle load balancing when calling the "my-service" endpoint, distributing the load among the specified server instances.</p>
<h2 id="heading-hystrix"><strong>Hystrix</strong></h2>
<p>Hystrix is a latency and fault tolerance library. It helps to prevent cascading failures in a microservices-based system by providing a fallback mechanism when a service fails. It also provides a circuit breaker pattern that can stop further calls to a service if it fails too many times, preventing the system from being overwhelmed by failed requests.</p>
<p>To integrate Hystrix with our Spring Boot application, we first need to add the Spring Cloud Netflix Hystrix dependency to our project.</p>
<pre><code class="lang-xml"><span class="hljs-tag">&lt;<span class="hljs-name">dependency</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">groupId</span>&gt;</span>org.springframework.cloud<span class="hljs-tag">&lt;/<span class="hljs-name">groupId</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">artifactId</span>&gt;</span>spring-cloud-starter-netflix-hystrix<span class="hljs-tag">&lt;/<span class="hljs-name">artifactId</span>&gt;</span>
<span class="hljs-tag">&lt;/<span class="hljs-name">dependency</span>&gt;</span>
</code></pre>
<p>Next, we need to use the <code>@HystrixCommand</code> annotation on the methods that call dependent services.</p>
<pre><code class="lang-java"><span class="hljs-meta">@HystrixCommand(fallbackMethod = "defaultFallbackMethod")</span>
<span class="hljs-function"><span class="hljs-keyword">public</span> String <span class="hljs-title">callDependentService</span><span class="hljs-params">()</span> </span>{
    <span class="hljs-keyword">return</span> restTemplate.getForObject(<span class="hljs-string">"http://my-service/endpoint"</span>, String.class);
}

<span class="hljs-function"><span class="hljs-keyword">public</span> String <span class="hljs-title">defaultFallbackMethod</span><span class="hljs-params">()</span> </span>{
    <span class="hljs-keyword">return</span> <span class="hljs-string">"Fallback method called."</span>;
}
</code></pre>
<p>With these configurations in place, Hystrix will automatically handle fallback and circuit breaker functionality when calling the "my-service" endpoint, providing a fallback mechanism when the service fails and preventing the system from being overwhelmed by failed requests.</p>
<h2 id="heading-zuul"><strong>Zuul</strong></h2>
<p>Zuul is a routing and filtering tool. It acts as a reverse proxy, routing incoming requests to the appropriate service and filtering requests based on specified rules. In a microservices-based system, Zuul can be used to handle authentication, rate limiting, and other request-level functionality that would otherwise need to be implemented in each service.</p>
<p>To integrate Zuul with our Spring Boot application, we first need to add the Spring Cloud Netflix Zuul dependency to our project.</p>
<pre><code class="lang-xml"><span class="hljs-tag">&lt;<span class="hljs-name">dependency</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">groupId</span>&gt;</span>org.springframework.cloud<span class="hljs-tag">&lt;/<span class="hljs-name">groupId</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">artifactId</span>&gt;</span>spring-cloud-starter-netflix-zuul<span class="hljs-tag">&lt;/<span class="hljs-name">artifactId</span>&gt;</span>
<span class="hljs-tag">&lt;/<span class="hljs-name">dependency</span>&gt;</span>
</code></pre>
<p>Next, we need to enable Zuul in our service by adding the <code>@EnableZuulProxy</code> annotation to our main class.</p>
<pre><code class="lang-java"><span class="hljs-meta">@SpringBootApplication</span>
<span class="hljs-meta">@EnableZuulProxy</span>
<span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">MyApplication</span> </span>{

    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> <span class="hljs-keyword">void</span> <span class="hljs-title">main</span><span class="hljs-params">(String[] args)</span> </span>{
        SpringApplication.run(MyApplication.class, args);
    }
}
</code></pre>
<p>We also need to configure the routing rules in our application properties.</p>
<pre><code class="lang-xml">zuul.routes.my-service.path=/my-service/**
zuul.routes.my-service.service-id=my-service
</code></pre>
<p>With these configurations in place, Zuul will handle routing incoming requests to the "my-service" endpoint to the appropriate service and filtering requests based on specified rules.</p>
<h2 id="heading-archaius"><strong>Archaius</strong></h2>
<p>Archaius is a configuration management tool. It allows for dynamic configuration of services and provides a consistent configuration across all instances of a service. In a microservices-based system, Archaius can be used to handle configuration changes without the need for a service restart.</p>
<p>To integrate Archaius with our Spring Boot application, we first need to add the Spring Cloud Netflix Archaius dependency to our project.</p>
<pre><code class="lang-xml"><span class="hljs-tag">&lt;<span class="hljs-name">dependency</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">groupId</span>&gt;</span>org.springframework.cloud<span class="hljs-tag">&lt;/<span class="hljs-name">groupId</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">artifactId</span>&gt;</span>spring-cloud-starter-netflix-archaius<span class="hljs-tag">&lt;/<span class="hljs-name">artifactId</span>&gt;</span>
<span class="hljs-tag">&lt;/<span class="hljs-name">dependency</span>&gt;</span>
</code></pre>
<p>Next, we need to enable Archaius in our service by adding the <code>@EnableArchaius</code> annotation to our main class.</p>
<pre><code class="lang-java"><span class="hljs-meta">@SpringBootApplication</span>
<span class="hljs-meta">@EnableArchaius</span>
<span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">MyApplication</span> </span>{

    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> <span class="hljs-keyword">void</span> <span class="hljs-title">main</span><span class="hljs-params">(String[] args)</span> </span>{
        SpringApplication.run(MyApplication.class, args);
    }
}
</code></pre>
<p>We also need to configure the Archaius properties in our application properties.</p>
<pre><code class="lang-xml">archaius.configurationSource.additionalUrls=file:///etc/config/application.properties
</code></pre>
<p>This configuration tells Archaius to read the additional configuration from the specified file location. Archaius also supports other sources of configuration like, AWS DynamoDB, Zookeeper, etc.</p>
<p>With these configurations in place, Archaius will handle dynamic configuration changes without the need for a service restart. This makes it easy to make changes to the configuration of a service without having to take it down for maintenance.</p>
<h2 id="heading-governator"><strong>Governator</strong></h2>
<p>Governator is a library that provides enhanced lifecycle management for applications. It is built on top of Google Guice and provides features such as annotation-based configuration, lifecycle callbacks, and JMX integration.</p>
<p>To use Governator in our Spring Boot application, we first need to add the following dependency to our project:</p>
<pre><code class="lang-xml"><span class="hljs-tag">&lt;<span class="hljs-name">dependency</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">groupId</span>&gt;</span>com.netflix.governator<span class="hljs-tag">&lt;/<span class="hljs-name">groupId</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">artifactId</span>&gt;</span>governator-core<span class="hljs-tag">&lt;/<span class="hljs-name">artifactId</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">version</span>&gt;</span>latest version<span class="hljs-tag">&lt;/<span class="hljs-name">version</span>&gt;</span>
<span class="hljs-tag">&lt;/<span class="hljs-name">dependency</span>&gt;</span>
</code></pre>
<p>Next, we can use Governator's annotation-based configuration feature by annotating our configuration class with <code>@ConfigurationProperties</code>.</p>
<pre><code class="lang-java"><span class="hljs-meta">@ConfigurationProperties</span>
<span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">MyConfiguration</span> </span>{
    <span class="hljs-keyword">private</span> String property1;
    <span class="hljs-keyword">private</span> <span class="hljs-keyword">int</span> property2;
    <span class="hljs-comment">//getters and setters</span>
}
</code></pre>
<p>We can also use Governator's lifecycle callbacks by implementing the <code>LifecycleListener</code> interface and registering it in our main class.</p>
<pre><code class="lang-java"><span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">MyLifecycleListener</span> <span class="hljs-keyword">implements</span> <span class="hljs-title">LifecycleListener</span> </span>{
    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">start</span><span class="hljs-params">()</span> <span class="hljs-keyword">throws</span> Exception </span>{
        <span class="hljs-comment">// do something on start</span>
    }
    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">stop</span><span class="hljs-params">()</span> <span class="hljs-keyword">throws</span> Exception </span>{
        <span class="hljs-comment">// do something on stop</span>
    }
}

<span class="hljs-meta">@SpringBootApplication</span>
<span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">MyApplication</span> </span>{
    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> <span class="hljs-keyword">void</span> <span class="hljs-title">main</span><span class="hljs-params">(String[] args)</span> </span>{
        Injector injector = LifecycleInjector.builder().withModules(<span class="hljs-keyword">new</span> MyModule()).build().createInjector();
        injector.getInstance(LifecycleManager.class).start();
    }
}
</code></pre>
<p>Governator also provides JMX integration by exposing the objects managed by Guice as MBeans, this way we can use JMX clients to monitor and manage our application.</p>
<h2 id="heading-scoop"><strong>Scoop</strong></h2>
<p>Scoop is a metrics aggregation tool. It can be used to collect, aggregate, and visualize metrics from multiple services in a microservices-based system. Scoop provides an HTTP endpoint that can be used to collect metrics from different services.</p>
<p>To use Scoop in our Spring Boot application, we first need to add the following dependency to our project:</p>
<pre><code class="lang-xml"><span class="hljs-tag">&lt;<span class="hljs-name">dependency</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">groupId</span>&gt;</span>com.netflix.scoop<span class="hljs-tag">&lt;/<span class="hljs-name">groupId</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">artifactId</span>&gt;</span>scoop-core<span class="hljs-tag">&lt;/<span class="hljs-name">artifactId</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">version</span>&gt;</span>latest version<span class="hljs-tag">&lt;/<span class="hljs-name">version</span>&gt;</span>
<span class="hljs-tag">&lt;/<span class="hljs-name">dependency</span>&gt;</span>
</code></pre>
<p>Next, we need to configure Scoop by adding the following properties to our application properties:</p>
<pre><code class="lang-xml">scoop.metrics.export.interval=10
scoop.metrics.export.endpoint=http://localhost:9090/metrics
</code></pre>
<p>This configuration tells Scoop to export metrics every 10 seconds to the specified endpoint. With this in place, our application will start exporting metrics to the specified endpoint, where they can be collected and aggregated by Scoop.</p>
<h2 id="heading-rxjava"><strong>RxJava</strong></h2>
<p>RxJava is a Java implementation of the ReactiveX programming model. It can be used to build highly concurrent, fault-tolerant, and responsive systems.</p>
<p>To use RxJava in our Spring Boot application, we first need to add the following dependency to our project:</p>
<pre><code class="lang-xml"><span class="hljs-tag">&lt;<span class="hljs-name">dependency</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">groupId</span>&gt;</span>io.reactivex.rxjava2<span class="hljs-tag">&lt;/<span class="hljs-name">groupId</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">artifactId</span>&gt;</span>rxjava<span class="hljs-tag">&lt;/<span class="hljs-name">artifactId</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">version</span>&gt;</span>latest version<span class="hljs-tag">&lt;/<span class="hljs-name">version</span>&gt;</span>
<span class="hljs-tag">&lt;/<span class="hljs-name">dependency</span>&gt;</span>
</code></pre>
<p>Once we have the dependency, we can start using RxJava's Observable and Observer classes to create reactive streams of data. For example, we can use the <code>Observable.create()</code> method to create an observable that emits a sequence of integers:</p>
<pre><code class="lang-java">Observable&lt;Integer&gt; observable = Observable.create(subscriber -&gt; {
    <span class="hljs-keyword">for</span> (<span class="hljs-keyword">int</span> i = <span class="hljs-number">0</span>; i &lt; <span class="hljs-number">10</span>; i++) {
        subscriber.onNext(i);
    }
    subscriber.onComplete();
});
</code></pre>
<p>We can then subscribe to this observable and consume the emitted items:</p>
<pre><code class="lang-java">observable.subscribe(<span class="hljs-keyword">new</span> Observer&lt;Integer&gt;() {
    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">onNext</span><span class="hljs-params">(Integer item)</span> </span>{
        System.out.println(<span class="hljs-string">"Next: "</span> + item);
    }
    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">onError</span><span class="hljs-params">(Throwable error)</span> </span>{
        System.err.println(<span class="hljs-string">"Error: "</span> + error.getMessage());
    }
    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">onComplete</span><span class="hljs-params">()</span> </span>{
        System.out.println(<span class="hljs-string">"Complete"</span>);
    }
});
</code></pre>
<p>RxJava also provides several operators that can be used to transform, filter, and combine observables. For example, we can use the <code>map()</code> operator to transform the items emitted by an observable:</p>
<pre><code class="lang-java">Observable&lt;String&gt; mappedObservable = observable.map(item -&gt; <span class="hljs-string">"Number: "</span> + item);
</code></pre>
<p>RxJava can be used to build highly concurrent, fault-tolerant, and responsive systems by providing an easy way to work with asynchronous data streams. It can be used in combination with other Netflix OSS tools like Hystrix to provide a complete solution for building resilient microservices.</p>
<h2 id="heading-conclusion">Conclusion</h2>
<p>Netflix OSS provides a rich set of tools and frameworks that can be used to build robust and scalable microservices-based systems. By integrating these tools into our Spring Boot application, we can leverage their capabilities to handle service discovery, load balancing, circuit breaker, routing, and dynamic configuration management. The tools and frameworks provided by Netflix OSS are battle-tested and widely used in production systems, making them a reliable choice for building microservices-based systems.</p>
<p>To further explore the usage of these tools and frameworks, I recommend checking out the official Netflix OSS documentation and the Spring Cloud Netflix documentation. Additionally, there are also many tutorials and examples available online that can help you get started with integrating Netflix OSS into your Spring Boot application.</p>
]]></content:encoded></item><item><title><![CDATA[JPA and Hibernate in Spring Boot for Beginners: A Comprehensive Guide]]></title><description><![CDATA[This tutorial is part of Springing into Action: A Spring Boot Journey from Novice to Pro Series, be sure to check it out for more related content!
Java Persistence API (JPA) is a Java specification for managing, persisting, and accessing data between...]]></description><link>https://amrtechuniverse.com/jpa-hibernate-spring-boot-beginners-guide</link><guid isPermaLink="true">https://amrtechuniverse.com/jpa-hibernate-spring-boot-beginners-guide</guid><category><![CDATA[Spring]]></category><category><![CDATA[Springboot]]></category><category><![CDATA[jpa]]></category><category><![CDATA[hibernate]]></category><category><![CDATA[Java]]></category><dc:creator><![CDATA[Amr Khaled]]></dc:creator><pubDate>Sun, 29 Jan 2023 15:00:39 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1674828402047/0219eac3-3926-4e0d-8c27-14875bd12347.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>This tutorial is part of <a target="_blank" href="https://amrtechuniverse.com/series/springboot-novice-to-pro"><strong>Springing into Action: A Spring Boot Journey from Novice to Pro</strong></a> Series, be sure to check it out for more related content!</p>
<p>Java Persistence API (JPA) is a Java specification for managing, persisting, and accessing data between Java objects/classes and a relational database. Hibernate is a popular implementation of the JPA specification and is widely used in the Java community. In this article, we will take a look at how to use JPA and Hibernate in Spring Boot applications with code examples and in-depth explanations.</p>
<h2 id="heading-why-use-jpa-and-hibernate-in-spring-boot"><strong>Why use JPA and Hibernate in Spring Boot?</strong></h2>
<p>JPA and Hibernate are great technologies for persisting data in a Java application. They provide a standard way of mapping Java objects to a relational database and allow for easy management of data in the application. Additionally, using JPA and Hibernate in a Spring Boot application allows for easy integration with other Spring features such as transactions and caching. They provide a simple and efficient way to manage data in a relational database. In this article, we will talk about setting up JPA &amp; Hibernate, creating Entities &amp; Repositories and then we will dive into the more advanced features of JPA and Hibernate, specifically custom queries and Hibernate Query Language (HQL).</p>
<h2 id="heading-setting-up-jpa-and-hibernate-in-spring-boot"><strong>Setting up JPA and Hibernate in Spring Boot</strong></h2>
<p>Before we can start using JPA and Hibernate in our Spring Boot application, we need to set up a few dependencies in our <code>pom.xml</code> file. First, we need to add the Spring Data JPA dependency:</p>
<pre><code class="lang-xml"><span class="hljs-tag">&lt;<span class="hljs-name">dependency</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">groupId</span>&gt;</span>org.springframework.boot<span class="hljs-tag">&lt;/<span class="hljs-name">groupId</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">artifactId</span>&gt;</span>spring-boot-starter-data-jpa<span class="hljs-tag">&lt;/<span class="hljs-name">artifactId</span>&gt;</span>
<span class="hljs-tag">&lt;/<span class="hljs-name">dependency</span>&gt;</span>
</code></pre>
<p>This dependency will bring in the necessary JPA and Hibernate libraries as well as the Spring Data JPA library, which provides easy integration with the JPA and Hibernate libraries.</p>
<p>Next, we need to add a database driver dependency. For example, if we are using MySQL, we would add the following dependency:</p>
<pre><code class="lang-xml"><span class="hljs-tag">&lt;<span class="hljs-name">dependency</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">groupId</span>&gt;</span>mysql<span class="hljs-tag">&lt;/<span class="hljs-name">groupId</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">artifactId</span>&gt;</span>mysql-connector-java<span class="hljs-tag">&lt;/<span class="hljs-name">artifactId</span>&gt;</span>
<span class="hljs-tag">&lt;/<span class="hljs-name">dependency</span>&gt;</span>
</code></pre>
<p>Once we have these dependencies set up, we can start configuring our application to use JPA and Hibernate.</p>
<h2 id="heading-configuring-jpa-and-hibernate"><strong>Configuring JPA and Hibernate</strong></h2>
<p>To configure JPA and Hibernate in our Spring Boot application, we need to create a <a target="_blank" href="http://application.properties"><code>application.properties</code></a> file in the <code>src/main/resources</code> directory. In this file, we will specify our database connection information and other JPA and Hibernate settings.</p>
<p>For example, to configure a MySQL database, we would add the following properties to our <a target="_blank" href="http://application.properties"><code>application.properties</code></a> file:</p>
<pre><code class="lang-plaintext">spring.datasource.url=jdbc:mysql://localhost:3306/dbname
spring.datasource.username=root
spring.datasource.password=password
spring.jpa.hibernate.ddl-auto=update
</code></pre>
<p>The <code>spring.datasource.url</code>, <code>spring.datasource.username</code>, and <code>spring.datasource.password</code> properties are used to configure the connection to the MySQL database. The <code>spring.jpa.hibernate.ddl-auto</code> property is used to configure Hibernate to automatically update the database schema.</p>
<h2 id="heading-creating-entities"><strong>Creating Entities</strong></h2>
<p>Now that we have our application configured to use JPA and Hibernate, we can start creating entities. Entities are plain old Java objects (POJOs) that represent the data in our application. They are annotated with JPA annotations to indicate how they should be mapped to the database.</p>
<p>For example, let's say we have a simple application that stores information about books. We could create a <code>Book</code> entity like this:</p>
<pre><code class="lang-java"><span class="hljs-meta">@Entity</span>
<span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Book</span> </span>{

    <span class="hljs-meta">@Id</span>
    <span class="hljs-meta">@GeneratedValue(strategy = GenerationType.IDENTITY)</span>
    <span class="hljs-keyword">private</span> Long id;

    <span class="hljs-keyword">private</span> String title;

    <span class="hljs-keyword">private</span> String author;

    <span class="hljs-keyword">private</span> String ISBN;

    <span class="hljs-comment">// Getters and setters</span>
}
</code></pre>
<p>The <code>@Entity</code> annotation indicates that this class is an entity and should be mapped to a database table. The <code>@Id</code> annotation indicates that the <code>id</code> field is the primary key for the table. The <code>@GeneratedValue</code> annotation is used to configure the primary key to be generated automatically by the database.</p>
<p>NOTE: You can use Lombok's annotations in conjunction with the above <code>@Entity</code> annotation to generate all the boilerplate code; if you want to learn more about the topic, you can check out my article <a target="_blank" href="https://amrtechuniverse.com/spring-boot-lombok-annotations-a-deeper-look">Spring Boot &amp; Lombok annotations: A deeper look</a></p>
<h2 id="heading-creating-repositories"><strong>Creating Repositories</strong></h2>
<p>Once we have our entities defined, we can start creating repositories. Repositories are used to interact with the data in the database. In Spring Data JPA, we can create a repository by creating an interface that extends the <code>JpaRepository</code> interface.</p>
<p>For example, to create a repository for our <code>Book</code> entity, we could create an interface like this:</p>
<pre><code class="lang-java"><span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">interface</span> <span class="hljs-title">BookRepository</span> <span class="hljs-keyword">extends</span> <span class="hljs-title">JpaRepository</span>&lt;<span class="hljs-title">Book</span>, <span class="hljs-title">Long</span>&gt; </span>{
}
</code></pre>
<p>This interface will provide basic CRUD functionality for our <code>Book</code> entity and can be easily injected into our service layer.</p>
<h2 id="heading-using-transactions"><strong>Using Transactions</strong></h2>
<p>JPA and Hibernate also provide support for transactions. Transactions are used to group multiple database operations together and ensure that they are either all committed or all rolled back. In a Spring Boot application, we can use the <code>@Transactional</code> annotation to indicate that a method should be executed within a transaction.</p>
<p>For example, let's say we have a service method that creates a new book:</p>
<pre><code class="lang-java"><span class="hljs-meta">@Service</span>
<span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">BookService</span> </span>{

    <span class="hljs-meta">@Autowired</span>
    <span class="hljs-keyword">private</span> BookRepository bookRepository;

    <span class="hljs-meta">@Transactional</span>
    <span class="hljs-function"><span class="hljs-keyword">public</span> Book <span class="hljs-title">createBook</span><span class="hljs-params">(String title, String author, String ISBN)</span> </span>{
        Book book = <span class="hljs-keyword">new</span> Book();
        book.setTitle(title);
        book.setAuthor(author);
        book.setISBN(ISBN);
        <span class="hljs-keyword">return</span> bookRepository.save(book);
    }
}
</code></pre>
<p>The <code>@Transactional</code> annotation on the <code>createBook</code> method indicates that the method should be executed within a transaction. This means that if an exception is thrown during the execution of the method, the database will roll back any changes made during the method.</p>
<h2 id="heading-custom-queries"><strong>Custom Queries</strong></h2>
<p>JPA provides a simple and convenient way to create custom queries using the <code>@Query</code> annotation. This annotation allows you to define a query directly in the repository interface, rather than in a separate class or XML file. The <code>@Query</code> annotation takes a single parameter, the query string. The query string can be written in either JPQL (Java Persistence Query Language) or SQL.</p>
<p>The following example shows how to use the <code>@Query</code> annotation to create a custom query that retrieves all users with a specific role:</p>
<pre><code class="lang-java"><span class="hljs-meta">@Repository</span>
<span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">interface</span> <span class="hljs-title">UserRepository</span> <span class="hljs-keyword">extends</span> <span class="hljs-title">JpaRepository</span>&lt;<span class="hljs-title">User</span>, <span class="hljs-title">Long</span>&gt; </span>{

    <span class="hljs-meta">@Query("SELECT u FROM User u WHERE u.role = ?1")</span>
    <span class="hljs-function">List&lt;User&gt; <span class="hljs-title">findByRole</span><span class="hljs-params">(String role)</span></span>;
}
</code></pre>
<p>In this example, the <code>findByRole</code> method is annotated with the <code>@Query</code> annotation and the query string is written in JPQL. The <code>?1</code> parameter is a positional parameter that is replaced with the value of the <code>role</code> argument when the query is executed.</p>
<p>It's also possible to use named parameters instead of positional parameters. Named parameters are prefixed with a <code>:</code> and can be used in the query string by referencing them by name. The following example shows how to use named parameters:</p>
<pre><code class="lang-java"><span class="hljs-meta">@Repository</span>
<span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">interface</span> <span class="hljs-title">UserRepository</span> <span class="hljs-keyword">extends</span> <span class="hljs-title">JpaRepository</span>&lt;<span class="hljs-title">User</span>, <span class="hljs-title">Long</span>&gt; </span>{

    <span class="hljs-meta">@Query("SELECT u FROM User u WHERE u.role = :role")</span>
    <span class="hljs-function">List&lt;User&gt; <span class="hljs-title">findByRole</span><span class="hljs-params">(<span class="hljs-meta">@Param("role")</span> String role)</span></span>;
}
</code></pre>
<p>It's important to note that the use of custom queries can result in more complex codebase and harder to maintain, that's why it is essential to use best practices and to write test cases to cover all the use cases.</p>
<h2 id="heading-hibernate-query-language-hql"><strong>Hibernate Query Language (HQL)</strong></h2>
<p>HQL is an object-oriented query language that is similar to SQL, but it operates on the objects of the persistent classes rather than on the database tables. HQL is used to create queries that are executed by the Hibernate framework.</p>
<p>The following example shows how to use HQL to create a query that retrieves all users with a specific role:</p>
<pre><code class="lang-java">Session session = sessionFactory.openSession();
Query query = session.createQuery(<span class="hljs-string">"FROM User WHERE role = :role"</span>);
query.setParameter(<span class="hljs-string">"role"</span>, <span class="hljs-string">"admin"</span>);
List&lt;User&gt; users = query.list();
</code></pre>
<p>In this example, the <code>createQuery</code> method is used to create a new query. The query string is written in HQL and the <code>:role</code> parameter is a named parameter that is replaced with the value of the <code>role</code> variable when the query is executed.</p>
<p>Using HQL can be more powerful than using JPA's <code>@Query</code> annotation, as it allows you to execute more complex queries and to use advanced features of the Hibernate framework. However, it can also result in more complex codebase and harder to maintain, that's why it's important to use it judiciously and with caution.</p>
<h2 id="heading-best-practices"><strong>Best Practices</strong></h2>
<p>When using custom queries and HQL in your SpringBoot application, there are a few best practices to keep in mind:</p>
<ol>
<li><p>Use parameter binding: Instead of concatenating variables into the query string, use parameter binding to prevent SQL injection attacks.</p>
</li>
<li><p>Keep queries simple: Complex queries can be difficult to maintain and may result in poor performance. Try to keep queries as simple as possible.</p>
</li>
<li><p>Use pagination: When retrieving large amounts of data, use pagination to limit the number of results returned and to improve performance.</p>
</li>
<li><p>Test your queries: Always test your queries to ensure that they are returning the expected results and to check for any performance issues.</p>
</li>
<li><p>Logging: Enable the logging of SQL statements to monitor the performance and identify any issues</p>
</li>
</ol>
<hr />
<h2 id="heading-conclusion"><strong>Conclusion</strong></h2>
<p>In this article, we delve into the advanced features of JPA and Hibernate in a Spring Boot application. We cover the setup and configuration of the necessary dependencies, as well as the creation of entities and repositories. Additionally, we explore the use of transactions and best practices for implementing custom queries and HQL. These features, when used correctly, can greatly improve the performance and efficiency of data retrieval operations in your application. It's important to keep in mind, however, that they should be used cautiously to maintain a maintainable codebase and optimal performance. By following the guidelines outlined in this article, you can harness the full potential of JPA and Hibernate in your Spring Boot application. As always, testing and monitoring your code is crucial to ensure optimal performance.</p>
]]></content:encoded></item><item><title><![CDATA[Game Of Threads: The Complete Guide]]></title><description><![CDATA[This tutorial is part of Springing into Action: A Spring Boot Journey from Novice to Pro Series, be sure to check it out for more related content!
Java is a powerful and versatile programming language, and one of its most powerful features is its sup...]]></description><link>https://amrtechuniverse.com/game-of-threads-the-complete-guide</link><guid isPermaLink="true">https://amrtechuniverse.com/game-of-threads-the-complete-guide</guid><category><![CDATA[Java]]></category><category><![CDATA[Threads]]></category><category><![CDATA[multithreading]]></category><dc:creator><![CDATA[Amr Khaled]]></dc:creator><pubDate>Sun, 29 Jan 2023 12:09:48 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1674994010020/c5dcdaff-51ee-4820-bd94-40368bb0869c.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>This tutorial is part of <a target="_blank" href="https://amrtechuniverse.com/series/springboot-novice-to-pro">Springing into Action: A Spring Boot Journey from Novice to Pro</a> Series, be sure to check it out for more related content!</p>
<p>Java is a powerful and versatile programming language, and one of its most powerful features is its support for multithreading. Multithreading allows a program to run multiple threads in parallel, which can greatly improve the performance and responsiveness of a program. In this article, we will take a comprehensive look at threads in Java 8+ and see how they can be used to improve the performance of a program.</p>
<h2 id="heading-what-are-threads"><strong>What are Threads?</strong></h2>
<p>A thread is a lightweight, independent unit of execution. It is a separate flow of control that runs in parallel with the main program. Each thread has its own stack, program counter, and local variables, which allows it to run independently of other threads. In Java, threads are implemented using the <code>Thread</code> class and the <code>Runnable</code> interface.</p>
<p>A <code>Thread</code> is a class in the Java standard library that represents a single thread of execution. A <code>Thread</code> object can be created and started using the <code>start()</code> method. A <code>Runnable</code> is an interface that defines a single method, <code>run()</code>, which is used to define the code that will be executed by the thread.</p>
<pre><code class="lang-java"><span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">MyThread</span> <span class="hljs-keyword">implements</span> <span class="hljs-title">Runnable</span> </span>{
    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">run</span><span class="hljs-params">()</span> </span>{
        <span class="hljs-comment">// Code to be executed by the thread</span>
    }
}
</code></pre>
<pre><code class="lang-java">Thread thread = <span class="hljs-keyword">new</span> Thread(<span class="hljs-keyword">new</span> MyThread());
thread.start();
</code></pre>
<h2 id="heading-thread-states"><strong>Thread States</strong></h2>
<p>A thread can be in one of several states, including:</p>
<ul>
<li><p><code>NEW</code>: The thread has been created but has not yet been started.</p>
</li>
<li><p><code>RUNNABLE</code>: The thread is running or is able to run.</p>
</li>
<li><p><code>BLOCKED</code>: The thread is blocked and is waiting for a lock or other resource.</p>
</li>
<li><p><code>WAITING</code>: The thread is waiting for another thread to perform a specific action.</p>
</li>
<li><p><code>TIMED_WAITING</code>: The thread is waiting for a specific amount of time.</p>
</li>
<li><p><code>TERMINATED</code>: The thread has completed execution.</p>
</li>
</ul>
<p>A thread's state can be accessed using the <code>getState()</code> method of the <code>Thread</code> class.</p>
<h2 id="heading-thread-priorities"><strong>Thread Priorities</strong></h2>
<p>In Java, threads can be assigned a priority, which determines the order in which they are executed. The <code>Thread</code> class defines several constants for the different priority levels, including <code>MIN_PRIORITY</code>, <code>NORM_PRIORITY</code>, and <code>MAX_PRIORITY</code>. The default priority for a new thread is <code>NORM_PRIORITY</code>.</p>
<pre><code class="lang-java">Thread thread = <span class="hljs-keyword">new</span> Thread(<span class="hljs-keyword">new</span> MyThread());
thread.setPriority(Thread.MIN_PRIORITY);
thread.start();
</code></pre>
<p>It's important to note that setting a thread's priority does not guarantee that it will be executed before other threads with lower priorities. The actual order in which threads are executed depends on the underlying operating system and the JVM's thread scheduler.</p>
<h2 id="heading-synchronization"><strong>Synchronization</strong></h2>
<p>Synchronization is a mechanism that allows multiple threads to access shared resources in a controlled manner. In Java, synchronization is achieved through the use of the <code>synchronized</code> keyword and the <code>Lock</code> and <code>Condition</code> interfaces.</p>
<h3 id="heading-synchronized-methods"><strong>Synchronized Methods</strong></h3>
<p>A synchronized method is a method that can only be executed by one thread at a time. To make a method synchronized, the <code>synchronized</code> keyword is used before the method's return type.</p>
<pre><code class="lang-java"><span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">MyThread</span> <span class="hljs-keyword">implements</span> <span class="hljs-title">Runnable</span> </span>{
    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">synchronized</span> <span class="hljs-keyword">void</span> <span class="hljs-title">run</span><span class="hljs-params">()</span> </span>{
<span class="hljs-comment">// Code to be executed by the thread</span>
}
}
</code></pre>
<p>When a thread enters a synchronized method, it acquires the lock for the object that the method belongs to. This means that no other thread can enter any synchronized method of that object until the first thread has exited the method and released the lock.</p>
<h3 id="heading-synchronized-blocks"><strong>Synchronized Blocks</strong></h3>
<p>In addition to synchronized methods, Java also supports synchronized blocks. A synchronized block is a block of code that can only be executed by one thread at a time. To create a synchronized block, the <code>synchronized</code> keyword is used followed by the object that the block will synchronize on.</p>
<p>This can be useful when you only need to synchronize a specific section of code rather than an entire method. For example:</p>
<pre><code class="lang-java"><span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">MyThread</span> <span class="hljs-keyword">implements</span> <span class="hljs-title">Runnable</span> </span>{
    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">run</span><span class="hljs-params">()</span> </span>{
        <span class="hljs-keyword">synchronized</span>(<span class="hljs-keyword">this</span>) {
            <span class="hljs-comment">// Code to be executed by the thread</span>
        }
    }
}
</code></pre>
<p>In the above example, we've created a synchronized block that synchronizes on the <code>this</code> object. This means that only one thread can execute the code inside the block at a time.</p>
<h3 id="heading-volatile-variables"><strong>Volatile Variables</strong></h3>
<p>Another way to control the visibility of variables between threads is by using the <code>volatile</code> keyword. A variable that is declared as <code>volatile</code> will have its value immediately visible to all other threads. This can be useful when multiple threads need to read and write to the same variable.</p>
<pre><code class="lang-java"><span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">MyThread</span> <span class="hljs-keyword">implements</span> <span class="hljs-title">Runnable</span> </span>{
    <span class="hljs-keyword">private</span> <span class="hljs-keyword">volatile</span> <span class="hljs-keyword">boolean</span> running = <span class="hljs-keyword">true</span>;
    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">run</span><span class="hljs-params">()</span> </span>{
        <span class="hljs-keyword">while</span>(running) {
            <span class="hljs-comment">// Code to be executed by the thread</span>
        }
    }
    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">stop</span><span class="hljs-params">()</span> </span>{
        running = <span class="hljs-keyword">false</span>;
    }
}
</code></pre>
<p>In the above example, we've created a <code>volatile</code> variable named <code>running</code>. This variable is used to control the execution of the <code>run()</code> method. When the <code>stop()</code> method is called, it sets the value of <code>running</code> to <code>false</code>, causing the thread to exit the while loop and end execution.</p>
<h3 id="heading-thread-pools"><strong>Thread Pools</strong></h3>
<p>Creating and managing threads can be a time-consuming and resource-intensive task. To help with this, Java provides a thread pooling mechanism through the <code>Executor</code> framework. A thread pool is a group of pre-initialized, reusable threads that can be used to execute multiple tasks simultaneously.</p>
<p>The <code>Executor</code> interface provides the <code>execute()</code> method for submitting tasks to be executed by a thread in the pool. The <code>Executors</code> class provides several methods for creating and managing thread pools, such as <code>newFixedThreadPool()</code> and <code>newCachedThreadPool()</code>.</p>
<pre><code class="lang-java">Executor executor = Executors.newFixedThreadPool(<span class="hljs-number">10</span>);
executor.execute(<span class="hljs-keyword">new</span> MyThread());
</code></pre>
<p>In the above example, we've created a fixed thread pool with a maximum of 10 threads. We then submit a task (an instance of <code>MyThread</code>) to be executed by a thread in the pool.</p>
<h1 id="heading-multithreading-issues">Multithreading Issues</h1>
<p>As we have seen, threading is a powerful feature that can greatly improve the performance and responsiveness of your applications. However, multithreading can also introduce new challenges, such as race conditions, deadlocks, and thread safety, that must be handled with proper care. In this section, we will delve deeper into these topics and explore solutions, best practices, and code examples for handling these challenges.</p>
<h2 id="heading-race-conditions"><strong>Race Conditions</strong></h2>
<p>A race condition occurs when multiple threads access shared resources simultaneously and the outcome of the program depends on the order in which the threads execute. This can lead to unexpected and unpredictable behavior, such as data corruption or incorrect results.</p>
<p>One common solution to race conditions is to use synchronization to control access to shared resources. The <code>synchronized</code> keyword can be used to create a critical section of code that can only be executed by one thread at a time. This ensures that only one thread can access the shared resource at a time, eliminating the possibility of a race condition.</p>
<pre><code class="lang-java"><span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">MyThread</span> <span class="hljs-keyword">implements</span> <span class="hljs-title">Runnable</span> </span>{
    <span class="hljs-keyword">private</span> List&lt;Integer&gt; sharedList = <span class="hljs-keyword">new</span> ArrayList&lt;&gt;();

    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">run</span><span class="hljs-params">()</span> </span>{
        <span class="hljs-keyword">synchronized</span>(sharedList) {
            <span class="hljs-comment">// Access shared resource</span>
            sharedList.add(Thread.currentThread().getId());
        }
    }
}
</code></pre>
<p>In the above example, we've created a <code>synchronized</code> block that synchronizes on the <code>sharedList</code> object. This means that only one thread can execute the code inside the block at a time, ensuring that the <code>sharedList</code> is not accessed simultaneously by multiple threads.</p>
<p>Another solution to race conditions is the use of the <code>Atomic</code> classes provided by the <code>java.util.concurrent.atomic</code> package. These classes provide a way to perform atomic operations on variables, such as incrementing or decrementing a value, without the need for explicit synchronization.</p>
<pre><code class="lang-java">AtomicInteger atomicInt = <span class="hljs-keyword">new</span> AtomicInteger();

<span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">increment</span><span class="hljs-params">()</span> </span>{
    atomicInt.incrementAndGet();
}
</code></pre>
<p>In the above example, we've created an <code>AtomicInteger</code> and we can increment it's value using <code>incrementAndGet</code> method which is an atomic operation that is guaranteed to be thread-safe.</p>
<h2 id="heading-deadlocks"><strong>Deadlocks</strong></h2>
<p>A deadlock occurs when two or more threads are blocked, waiting for each other to release a resource. This results in the threads being unable to proceed, effectively locking the program.</p>
<p>One solution to deadlocks is to use a <code>Lock</code> object instead of the <code>synchronized</code> keyword. A <code>Lock</code> object provides more fine-grained control over thread synchronization and also provides a way to detect and recover from deadlocks.</p>
<pre><code class="lang-java"><span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">MyThread</span> <span class="hljs-keyword">implements</span> <span class="hljs-title">Runnable</span> </span>{
    <span class="hljs-keyword">private</span> Lock lock1 = <span class="hljs-keyword">new</span> ReentrantLock();
    <span class="hljs-keyword">private</span> Lock lock2 = <span class="hljs-keyword">new</span> ReentrantLock();

    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">run</span><span class="hljs-params">()</span> </span>{
        lock1.lock();
        <span class="hljs-keyword">try</span> {
            <span class="hljs-comment">// Access shared resource</span>
            lock2.lock();
            <span class="hljs-keyword">try</span> {
                <span class="hljs-comment">// Access shared resource</span>
            } <span class="hljs-keyword">finally</span> {
                lock2.unlock();
            }
        } <span class="hljs-keyword">finally</span> {
            lock1.unlock();
        }
    }
}
</code></pre>
<p>In the above example, we've created two <code>Lock</code> objects and used them to control access to the shared resources. By using the <code>try-finally</code> pattern, we ensure that the locks are always released, even if an exception is thrown. This helps to prevent deadlocks caused by threads holding on to resources indefinitely.</p>
<p>Another solution to deadlocks is to use the <code>Lock.tryLock()</code> method, which attempts to acquire a lock and returns immediately with a boolean value indicating whether the lock was acquired or not. This can be used to implement a timeout mechanism for acquiring locks, which can help to avoid deadlocks caused by threads waiting for resources that will never be released.</p>
<pre><code class="lang-java"><span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">MyThread</span> <span class="hljs-keyword">implements</span> <span class="hljs-title">Runnable</span> </span>{
    <span class="hljs-keyword">private</span> Lock lock = <span class="hljs-keyword">new</span> ReentrantLock();

    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">run</span><span class="hljs-params">()</span> </span>{
        <span class="hljs-keyword">if</span> (lock.tryLock(<span class="hljs-number">1</span>, TimeUnit.SECONDS)) {
            <span class="hljs-keyword">try</span> {
                <span class="hljs-comment">// Access shared resource</span>
            } <span class="hljs-keyword">finally</span> {
                lock.unlock();
            }
        } <span class="hljs-keyword">else</span> {
            <span class="hljs-comment">// Handle failure to acquire lock</span>
        }
    }
}
</code></pre>
<p>In the above example, we've used the <code>tryLock</code> method to attempt to acquire the lock with a timeout of 1 second. If the lock is acquired, the thread can access the shared resource. If the lock is not acquired within the timeout period, the thread can handle the failure and take appropriate action, such as retrying later or giving up.</p>
<h2 id="heading-thread-safety"><strong>Thread-safety</strong></h2>
<p>Thread-safety is the property of an object or a class that can be safely accessed by multiple threads without causing unexpected behavior. To ensure thread-safety, we can use the same solutions as mentioned above: synchronization and atomic variables, as well as using thread-safe collections from <code>java.util.concurrent</code> package.</p>
<pre><code class="lang-java"><span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">MyThreadSafeClass</span> </span>{
    <span class="hljs-keyword">private</span> AtomicInteger atomicInt = <span class="hljs-keyword">new</span> AtomicInteger();
    <span class="hljs-keyword">private</span> ConcurrentHashMap&lt;String, String&gt; threadSafeMap = <span class="hljs-keyword">new</span> ConcurrentHashMap&lt;&gt;();

    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">increment</span><span class="hljs-params">()</span> </span>{
        atomicInt.incrementAndGet();
    }

    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">put</span><span class="hljs-params">(String key, String value)</span> </span>{
        threadSafeMap.put(key, value);
    }
}
</code></pre>
<p>In the above example, we've used an <code>AtomicInteger</code> to ensure that the <code>increment</code> method is thread-safe and a <code>ConcurrentHashMap</code> to ensure that the <code>put</code> method is thread-safe.</p>
<h2 id="heading-conclusion"><strong>Conclusion</strong></h2>
<p>Threading can greatly improve the performance and responsiveness of your applications, but it also introduces new challenges such as race conditions, deadlocks, and thread-safety that must be handled with proper care. In this article, we covered the basics of thread creation, synchronization, and thread pools in Java 8+ to create robust and efficient concurrent applications. Additionally, we explored solutions, best practices, and code examples for handling the challenges of multithreading such as using synchronization, atomic variables, and thread-safe collections. By understanding and applying these techniques, you can develop multithreaded applications that are both efficient and safe. I hope this article has provided you with a solid foundation for working with threads in your own Java applications.</p>
]]></content:encoded></item><item><title><![CDATA[Spring Boot & Lombok annotations: A deeper look]]></title><description><![CDATA[This tutorial is part of Springing into Action: A Spring Boot Journey from Novice to Pro Series, be sure to check it out for more related content!
Spring Boot and Lombok are two popular frameworks used in Java development. They both provide a set of ...]]></description><link>https://amrtechuniverse.com/spring-boot-lombok-annotations-a-deeper-look</link><guid isPermaLink="true">https://amrtechuniverse.com/spring-boot-lombok-annotations-a-deeper-look</guid><category><![CDATA[Springboot]]></category><category><![CDATA[Spring]]></category><category><![CDATA[Java]]></category><category><![CDATA[lombok]]></category><category><![CDATA[Web Development]]></category><dc:creator><![CDATA[Amr Khaled]]></dc:creator><pubDate>Fri, 27 Jan 2023 11:00:39 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1674651607825/7808c085-9c0c-4aea-9070-306d8705cc53.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>This tutorial is part of <a target="_blank" href="https://amrtechuniverse.com/series/springboot-novice-to-pro"><strong>Springing into Action: A Spring Boot Journey from Novice to Pro</strong></a> Series, be sure to check it out for more related content!</p>
<p>Spring Boot and Lombok are two popular frameworks used in Java development. They both provide a set of annotations that can make your code more concise and readable. In this article, we will take a deeper look at some of the most commonly used annotations in Spring Boot and Lombok, their uses and how they can help you write better code.</p>
<h2 id="heading-spring-boot-annotations">Spring Boot Annotations</h2>
<ul>
<li><p><code>@SpringBootApplication</code>: This is a convenience annotation that is equivalent to including the <code>@Configuration</code>, <code>@EnableAutoConfiguration</code>, and <code>@ComponentScan</code> annotations. It is used to enable auto-configuration and component scanning in your application.</p>
<pre><code class="lang-java">  <span class="hljs-meta">@SpringBootApplication</span> <span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Application</span> </span>{     
      <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> <span class="hljs-keyword">void</span> <span class="hljs-title">main</span><span class="hljs-params">(String[] args)</span> </span>{ 
          SpringApplication.run(Application.class, args);     
      } 
  }
</code></pre>
</li>
<li><p><code>@RestController</code>: This annotation is used to create a RESTful controller in Spring Boot. It is a combination of the <code>@Controller</code> and <code>@ResponseBody</code> annotations.</p>
<pre><code class="lang-java">  <span class="hljs-meta">@RestController</span>
  <span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">MyController</span> </span>{
      <span class="hljs-meta">@GetMapping("/")</span>
      <span class="hljs-function"><span class="hljs-keyword">public</span> String <span class="hljs-title">home</span><span class="hljs-params">()</span> </span>{
          <span class="hljs-keyword">return</span> <span class="hljs-string">"Hello, World!"</span>;
      }
  }
</code></pre>
</li>
</ul>
<ul>
<li><p><code>@RestControllerAdvice</code>: This annotation is used to handle the global exception handling in the application.</p>
<pre><code class="lang-java">  <span class="hljs-meta">@RestControllerAdvice</span>
  <span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">ExceptionAdvice</span> </span>{
      <span class="hljs-meta">@ExceptionHandler(value = Exception.class)</span>
      <span class="hljs-function"><span class="hljs-keyword">public</span> ResponseEntity&lt;Object&gt; <span class="hljs-title">handleException</span><span class="hljs-params">(Exception ex)</span> </span>{
          <span class="hljs-keyword">return</span> <span class="hljs-keyword">new</span> ResponseEntity&lt;&gt;(ex.getMessage(), HttpStatus.INTERNAL_SERVER_ERROR);
      }
  }
</code></pre>
</li>
<li><p><code>@Autowired</code>: This annotation is used to inject a dependency into a class. It can be used on fields, methods, or constructors.</p>
<pre><code class="lang-java">  <span class="hljs-meta">@Service</span>
  <span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">MyService</span> </span>{
      <span class="hljs-meta">@Autowired</span>
      <span class="hljs-keyword">private</span> MyRepository myRepository;
  }
</code></pre>
</li>
</ul>
<ul>
<li><p><code>@Value</code>: This annotation is used to assign a value to a field from a properties file.</p>
<pre><code class="lang-java">  <span class="hljs-meta">@Value("${app.name}")</span>
  <span class="hljs-keyword">private</span> String appName;
</code></pre>
</li>
<li><p><code>@PostConstruct</code>: This annotation is used to indicate a method to be executed after the bean is created and all the dependencies are injected.</p>
<pre><code class="lang-java">  <span class="hljs-meta">@Service</span>
  <span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">MyService</span> </span>{
      <span class="hljs-meta">@Autowired</span>
      <span class="hljs-keyword">private</span> MyRepository myRepository;

      <span class="hljs-meta">@PostConstruct</span>
      <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">init</span><span class="hljs-params">()</span> </span>{
          <span class="hljs-comment">//some initialization code</span>
      }
  }
</code></pre>
</li>
</ul>
<h2 id="heading-lombok-annotations"><strong>Lombok Annotations</strong></h2>
<ul>
<li><p><code>@Data</code>: This annotation generates getters and setters, <code>toString</code>, <code>equals</code>, and <code>hashCode</code> methods for a class.</p>
<pre><code class="lang-java">  <span class="hljs-meta">@Data</span>
  <span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Student</span> </span>{
      <span class="hljs-keyword">private</span> Long id;
      <span class="hljs-keyword">private</span> String name;
  }
</code></pre>
</li>
<li><p><code>@NoArgsConstructor</code>: This annotation generates a constructor with no arguments.</p>
<pre><code class="lang-java">  <span class="hljs-meta">@NoArgsConstructor</span>
  <span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Student</span> </span>{
      <span class="hljs-keyword">private</span> Long id;
      <span class="hljs-keyword">private</span> String name;
  }
</code></pre>
</li>
<li><p><code>@AllArgsConstructor</code>: This annotation generates a constructor with all fields as arguments.</p>
<pre><code class="lang-java">  <span class="hljs-meta">@AllArgsConstructor</span>
  <span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Student</span> </span>{
      <span class="hljs-keyword">private</span> Long id;
      <span class="hljs-keyword">private</span> String name;
  }
</code></pre>
</li>
<li><p><code>@Builder</code> : This annotation generates a builder pattern for a class</p>
<pre><code class="lang-java">  <span class="hljs-meta">@Builder</span>
  <span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Student</span> </span>{
      <span class="hljs-keyword">private</span> Long id;
      <span class="hljs-keyword">private</span> String name;
  }
</code></pre>
</li>
<li><p><code>@Slf4j</code>: This annotation is used to generate a logger for the class</p>
<pre><code class="lang-java">  <span class="hljs-meta">@Slf4j</span>
  <span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">MyService</span> </span>{
      <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">myMethod</span><span class="hljs-params">()</span> </span>{
          log.info(<span class="hljs-string">"This is an example of log"</span>);
      }
  }
</code></pre>
</li>
</ul>
<p>These are just a few examples of the annotations provided by Spring Boot and Lombok. Using these annotations can help you write cleaner and more readable code, making it easier to maintain and understand.</p>
<p>In conclusion, Spring Boot and Lombok are powerful tools that can help you to write better code and improve your productivity as a developer. With the help of annotations, you can make your code more readable and maintainable. I hope this article has been helpful in introducing some of the most useful annotations provided by these frameworks.</p>
]]></content:encoded></item><item><title><![CDATA[Creating a Simple Application with Spring Boot and JPA Repository]]></title><description><![CDATA[This tutorial is part of Springing into Action: A Spring Boot Journey from Novice to Pro Series, be sure to check it out for more related content!
In this tutorial, we will learn how to create a simple application using Spring Boot and JPA Repository...]]></description><link>https://amrtechuniverse.com/creating-a-simple-application-with-spring-boot-and-jpa-repository</link><guid isPermaLink="true">https://amrtechuniverse.com/creating-a-simple-application-with-spring-boot-and-jpa-repository</guid><category><![CDATA[Springboot]]></category><category><![CDATA[Spring]]></category><category><![CDATA[jpa]]></category><category><![CDATA[Spring Data Jpa]]></category><category><![CDATA[Java]]></category><dc:creator><![CDATA[Amr Khaled]]></dc:creator><pubDate>Thu, 26 Jan 2023 12:00:39 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1674646516967/a466a29c-8cb9-414d-9a2b-decf4de67a29.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>This tutorial is part of <a target="_blank" href="https://amrtechuniverse.com/series/springboot-novice-to-pro">Springing into Action: A Spring Boot Journey from Novice to Pro</a> Series, be sure to check it out for more related content!</p>
<p>In this tutorial, we will learn how to create a simple application using Spring Boot and JPA Repository, including pagination. We will use a MySQL database to persist our data and will create a REST API to perform CRUD operations on it.</p>
<h2 id="heading-prerequisites"><strong>Prerequisites</strong></h2>
<ul>
<li><p>Java 8 or later</p>
</li>
<li><p>Maven 3.x</p>
</li>
<li><p>MySQL Server</p>
</li>
<li><p>Spring Boot CLI</p>
</li>
<li><p>An IDE like Eclipse or IntelliJ IDEA</p>
</li>
</ul>
<h2 id="heading-setting-up-the-project"><strong>Setting up the Project</strong></h2>
<p>First, we need to create a new Spring Boot project using the Spring Initializer. We will select the following dependencies:</p>
<ul>
<li><p>Spring Web</p>
</li>
<li><p>Spring Data JPA</p>
</li>
<li><p>MySQL Driver</p>
</li>
</ul>
<p>Once the project is generated, we can import it into our IDE and start adding our code.</p>
<h2 id="heading-configuring-the-database"><strong>Configuring the Database</strong></h2>
<p>Next, we will configure our MySQL database by adding the following properties to our <a target="_blank" href="http://application.properties"><code>application.properties</code></a> file:</p>
<pre><code class="lang-java">spring.datasource.url=jdbc:mysql:<span class="hljs-comment">//&lt;host&gt;:&lt;port&gt;/&lt;dbname&gt;</span>
spring.datasource.username=&lt;username&gt;
spring.datasource.password=&lt;password&gt;
</code></pre>
<p>Make sure to replace the placeholders with the appropriate values for your MySQL server.</p>
<h2 id="heading-creating-the-entity"><strong>Creating the Entity</strong></h2>
<p>We will create two entities, <code>Student</code> and <code>Course</code>, to represent our data. The <code>Student</code> entity will have a one-to-many relationship with the <code>Course</code> entity.</p>
<pre><code class="lang-java"><span class="hljs-meta">@Entity</span>
<span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Student</span> </span>{
    <span class="hljs-meta">@Id</span>
    <span class="hljs-meta">@GeneratedValue(strategy = GenerationType.IDENTITY)</span>
    <span class="hljs-keyword">private</span> Long id;
    <span class="hljs-keyword">private</span> String name;
    <span class="hljs-meta">@OneToMany(mappedBy = "student", cascade = CascadeType.ALL, fetch = FetchType.LAZY)</span>
    <span class="hljs-keyword">private</span> List&lt;Course&gt; courses;
    <span class="hljs-comment">// getters and setters</span>
}
</code></pre>
<pre><code class="lang-java"><span class="hljs-meta">@Entity</span>
<span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Course</span> </span>{
    <span class="hljs-meta">@Id</span>
    <span class="hljs-meta">@GeneratedValue(strategy = GenerationType.IDENTITY)</span>
    <span class="hljs-keyword">private</span> Long id;
    <span class="hljs-keyword">private</span> String name;
    <span class="hljs-meta">@ManyToOne</span>
    <span class="hljs-meta">@JoinColumn(name = "student_id")</span>
    <span class="hljs-keyword">private</span> Student student;
    <span class="hljs-comment">// getters and setters</span>
}
</code></pre>
<h2 id="heading-creating-the-repository"><strong>Creating the Repository</strong></h2>
<p>We will create a JPA repository for each entity to perform CRUD operations on our data.</p>
<pre><code class="lang-java"><span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">interface</span> <span class="hljs-title">StudentRepository</span> <span class="hljs-keyword">extends</span> <span class="hljs-title">JpaRepository</span>&lt;<span class="hljs-title">Student</span>, <span class="hljs-title">Long</span>&gt; </span>{
}
</code></pre>
<pre><code class="lang-java"><span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">interface</span> <span class="hljs-title">CourseRepository</span> <span class="hljs-keyword">extends</span> <span class="hljs-title">JpaRepository</span>&lt;<span class="hljs-title">Course</span>, <span class="hljs-title">Long</span>&gt; </span>{
}
</code></pre>
<h2 id="heading-creating-the-rest-api"><strong>Creating the REST API</strong></h2>
<p>We will create a REST controller for each entity to handle the HTTP requests.</p>
<pre><code class="lang-java"><span class="hljs-meta">@RestController</span>
<span class="hljs-meta">@RequestMapping("/students")</span>
<span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">StudentController</span> </span>{
    <span class="hljs-meta">@Autowired</span>
    <span class="hljs-keyword">private</span> StudentRepository studentRepository;
    <span class="hljs-meta">@Autowired</span>
    <span class="hljs-keyword">private</span> CourseRepository courseRepository;

    <span class="hljs-meta">@GetMapping</span>
    <span class="hljs-function"><span class="hljs-keyword">public</span> Page&lt;Student&gt; <span class="hljs-title">getAllStudents</span><span class="hljs-params">(Pageable pageable)</span> </span>{
        <span class="hljs-keyword">return</span> studentRepository.findAll(pageable);
    }

    <span class="hljs-meta">@PostMapping</span>
    <span class="hljs-function"><span class="hljs-keyword">public</span> Student <span class="hljs-title">addStudent</span><span class="hljs-params">(<span class="hljs-meta">@RequestBody</span> Student student)</span> </span>{
        <span class="hljs-keyword">return</span> studentRepository.save(student);
    }

    <span class="hljs-meta">@PutMapping("/{studentId}")</span>
    <span class="hljs-function"><span class="hljs-keyword">public</span> Student <span class="hljs-title">updateStudent</span><span class="hljs-params">(<span class="hljs-meta">@PathVariable</span> Long studentId, <span class="hljs-meta">@RequestBodyStudent</span> student)</span> </span>{
 student.setId(studentId); <span class="hljs-keyword">return</span> studentRepository.save(student); }

<span class="hljs-meta">@DeleteMapping("/{studentId}")</span>
<span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">deleteStudent</span><span class="hljs-params">(<span class="hljs-meta">@PathVariable</span> Long studentId)</span> </span>{
    studentRepository.deleteById(studentId);
}

<span class="hljs-meta">@GetMapping("/{studentId}/courses")</span>
<span class="hljs-function"><span class="hljs-keyword">public</span> List&lt;Course&gt; <span class="hljs-title">getStudentCourses</span><span class="hljs-params">(<span class="hljs-meta">@PathVariable</span> Long studentId)</span> </span>{
    <span class="hljs-keyword">return</span> courseRepository.findByStudentId(studentId);
}
}
</code></pre>
<pre><code class="lang-java">
<span class="hljs-meta">@RestController</span>
<span class="hljs-meta">@RequestMapping("/courses")</span>
<span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">CourseController</span> </span>{
    <span class="hljs-meta">@Autowired</span>
    <span class="hljs-keyword">private</span> CourseRepository courseRepository;

    <span class="hljs-meta">@GetMapping</span>
    <span class="hljs-function"><span class="hljs-keyword">public</span> Page&lt;Course&gt; <span class="hljs-title">getAllCourses</span><span class="hljs-params">(Pageable pageable)</span> </span>{
        <span class="hljs-keyword">return</span> courseRepository.findAll(pageable);
    }

    <span class="hljs-meta">@PostMapping</span>
    <span class="hljs-function"><span class="hljs-keyword">public</span> Course <span class="hljs-title">addCourse</span><span class="hljs-params">(<span class="hljs-meta">@RequestBody</span> Course course)</span> </span>{
        <span class="hljs-keyword">return</span> courseRepository.save(course);
    }

    <span class="hljs-meta">@PutMapping("/{courseId}")</span>
    <span class="hljs-function"><span class="hljs-keyword">public</span> Course <span class="hljs-title">updateCourse</span><span class="hljs-params">(<span class="hljs-meta">@PathVariable</span> Long courseId, <span class="hljs-meta">@RequestBody</span> Course course)</span> </span>{
        course.setId(courseId);
        <span class="hljs-keyword">return</span> courseRepository.save(course);
    }

    <span class="hljs-meta">@DeleteMapping("/{courseId}")</span>
    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">deleteCourse</span><span class="hljs-params">(<span class="hljs-meta">@PathVariable</span> Long courseId)</span> </span>{
        courseRepository.deleteById(courseId);
    }
}
</code></pre>
<p>In the above code examples, we have added pagination by passing a <code>Pageable</code> object to our repository's <code>findAll()</code> method. This allows us to retrieve a specific page of data from our database.</p>
<h2 id="heading-running-the-application"><strong>Running the Application</strong></h2>
<p>Once the project is set up, we can run it using the following command:</p>
<pre><code class="lang-java">mvn spring-boot:run
</code></pre>
<p>We can now test our REST API by sending HTTP requests to the appropriate endpoints.</p>
<p>In this tutorial, we have learned how to create a simple application using Spring Boot and JPA Repository, including pagination. We have also seen how easy it is to perform CRUD operations on a MySQL database using this framework.</p>
<p>I hope you found this tutorial helpful, and that you can use this as a starting point for your next project.</p>
<p>Note: above code is a simplified version for demonstration purposes, it's not ready to use code, you may need to customize it according to your requirement.</p>
]]></content:encoded></item><item><title><![CDATA[Dependency Injection, Circular References, and Spring Bean Life Cycle: A Comprehensive Guide]]></title><description><![CDATA[This tutorial is part of Springing into Action: A Spring Boot Journey from Novice to Pro Series, be sure to check it out for more related content!
Dependency Injection (DI) is a fundamental concept in software development that allows objects to be de...]]></description><link>https://amrtechuniverse.com/dependency-injection-circular-references-and-spring-bean-life-cycle-a-comprehensive-guide</link><guid isPermaLink="true">https://amrtechuniverse.com/dependency-injection-circular-references-and-spring-bean-life-cycle-a-comprehensive-guide</guid><category><![CDATA[Springboot]]></category><category><![CDATA[Spring]]></category><category><![CDATA[Web Development]]></category><category><![CDATA[dependency injection]]></category><category><![CDATA[Java]]></category><dc:creator><![CDATA[Amr Khaled]]></dc:creator><pubDate>Wed, 25 Jan 2023 13:37:24 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1674653678552/bf9fdbdb-5a76-4a0b-aeda-1990d9027522.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>This tutorial is part of <a target="_blank" href="https://amrtechuniverse.com/series/springboot-novice-to-pro"><strong>Springing into Action: A Spring Boot Journey from Novice to Pro</strong></a> Series, be sure to check it out for more related content!</p>
<p>Dependency Injection (DI) is a fundamental concept in software development that allows objects to be decoupled from their dependencies. In Spring, DI is achieved through the use of the <code>@Autowired</code> annotation, which can be applied to fields, methods, or constructors. DI is a powerful technique that can help you to write more maintainable and testable code.</p>
<p>However, when not used correctly, DI can lead to circular references. A circular reference occurs when two or more beans depend on each other, creating a cycle that cannot be resolved. In Spring, circular references can be detected and resolved through the use of <code>@Lazy</code>, <code>@Primary</code>, or <code>@DependsOn</code> annotations.</p>
<p>In addition to DI and circular references, understanding the Spring Bean Life Cycle is also important for developing robust and maintainable applications. The Spring Bean Life Cycle consists of several phases, including instantiation, dependency injection, initialization, and destruction. Understanding these phases and how to use annotations such as <code>@PostConstruct</code> and <code>@PreDestroy</code> can help you to write more efficient and effective code.</p>
<p>In this article, we will explore these topics in greater depth, providing examples and best practices for each.</p>
<h2 id="heading-dependency-injection"><strong>Dependency Injection</strong></h2>
<p>Dependency Injection is a design pattern that allows objects to be decoupled from their dependencies. In Spring, this is achieved through the use of the <code>@Autowired</code> annotation.</p>
<p>The <code>@Autowired</code> annotation can be applied to fields, methods, or constructors, and is used to inject a dependency into a class. For example, if we have a <code>MyService</code> class that depends on a <code>MyRepository</code> class, we can use the <code>@Autowired</code> annotation to inject the <code>MyRepository</code> dependency into the <code>MyService</code> class:</p>
<pre><code class="lang-java"><span class="hljs-meta">@Service</span>
<span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">MyService</span> </span>{
    <span class="hljs-meta">@Autowired</span>
    <span class="hljs-keyword">private</span> MyRepository myRepository;

    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">doSomething</span><span class="hljs-params">()</span> </span>{
        <span class="hljs-comment">// use myRepository here</span>
    }
}
</code></pre>
<p>In the above example, the <code>MyService</code> class is annotated with <code>@Service</code> which tells Spring to create an instance of this class as a bean, and <code>MyRepository</code> class is also annotated with <code>@Repository</code> which tells Spring to create an instance of this class as a bean and the <code>MyRepository</code> bean is injected into the <code>MyService</code> bean.</p>
<p>We can also use the <code>@Autowired</code> annotation on constructors and methods. For example, instead of using the annotation on a field, we can use it on a constructor or method like this:</p>
<pre><code class="lang-java"><span class="hljs-meta">@Service</span>
<span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">MyService</span> </span>{
    <span class="hljs-keyword">private</span> <span class="hljs-keyword">final</span> MyRepository myRepository;

    <span class="hljs-meta">@Autowired</span>
    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-title">MyService</span><span class="hljs-params">(MyRepository myRepository)</span> </span>{
        <span class="hljs-keyword">this</span>.myRepository = myRepository;
    }
    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">doSomething</span><span class="hljs-params">()</span> </span>{
        <span class="hljs-comment">// use myRepository here</span>
    }
}
</code></pre>
<p>In this example, Spring will automatically call the constructor with the <code>MyRepository</code> bean as its argument, and the <code>myRepository</code> field will be initialized with the injected dependency.</p>
<p>It's also worth noting that Spring also provides other annotations for injecting dependencies, such as <code>@Resource</code>, <code>@Inject</code>, and <code>@Qualifier</code>. These annotations can be used in similar ways as <code>@Autowired</code>, but they have some small differences. <code>@Resource</code> and <code>@Inject</code> are part of Java's standard annotation library, while <code>@Autowired</code> is specific to the Spring framework. <code>@Qualifier</code> can be used in conjunction with <code>@Autowired</code> to disambiguate between multiple beans of the same type.</p>
<pre><code class="lang-java"><span class="hljs-meta">@Service</span>
<span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">MyService</span> </span>{
    <span class="hljs-meta">@Autowired</span>
    <span class="hljs-meta">@Qualifier("myRepository")</span>
    <span class="hljs-keyword">private</span> MyRepository myRepository;
}
</code></pre>
<p>In the above example, <code>@Qualifier</code> is used to specify that the <code>myRepository</code> bean should be injected, rather than any other bean of type <code>MyRepository</code>.</p>
<h3 id="heading-best-practices"><strong>Best Practices</strong></h3>
<ul>
<li><p>Use constructor injection where possible, as it makes the code more readable and testable.</p>
</li>
<li><p>Use field injection only as a last resort, as it can make the code harder to understand and test.</p>
</li>
<li><p>Avoid using setter injection, as it can lead to tight coupling between classes.</p>
</li>
<li><p>Use <code>@Qualifier</code> to disambiguate between multiple beans of the same type.</p>
</li>
<li><p>Use <code>@Primary</code> or <code>@Lazy</code> to resolve circular references.</p>
</li>
</ul>
<h2 id="heading-circular-references"><strong>Circular References</strong></h2>
<p>A circular reference occurs when two or more beans depend on each other, creating a cycle that cannot be resolved. In Spring, circular references can be detected and resolved through the use of <code>@Lazy</code>, <code>@Primary</code>, or <code>@DependsOn</code> annotations.</p>
<p>The <code>@Lazy</code> annotation can be used to delay the initialization of a bean until it is needed. For example, if we have a <code>MyService</code> class that depends on a <code>MyRepository</code> class, and the <code>MyRepository</code> class depends on the <code>MyService</code> class, we can use the <code>@Lazy</code> annotation on one of the dependencies to break the cycle:</p>
<pre><code class="lang-java"><span class="hljs-meta">@Service</span>
<span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">MyService</span> </span>{
    <span class="hljs-meta">@Autowired</span>
    <span class="hljs-meta">@Lazy</span>
    <span class="hljs-keyword">private</span> MyRepository myRepository;
}

<span class="hljs-meta">@Repository</span>
<span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">MyRepository</span> </span>{
    <span class="hljs-meta">@Autowired</span>
    <span class="hljs-keyword">private</span> MyService myService;
}
</code></pre>
<p>In this example, the <code>MyService</code> bean will not be initialized until it is actually needed, thus breaking the circular reference.</p>
<p>The <code>@Primary</code> annotation can be used to specify that a particular bean should be used by default when multiple beans of the same type are found. For example, if we have two <code>MyRepository</code> beans, one annotated with <code>@Primary</code> and one without, the bean annotated with <code>@Primary</code> will be used by default.</p>
<pre><code class="lang-java"><span class="hljs-meta">@Repository</span>
<span class="hljs-meta">@Primary</span>
<span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">MyRepositoryImpl1</span> <span class="hljs-keyword">implements</span> <span class="hljs-title">MyRepository</span> </span>{
    <span class="hljs-comment">//implementation</span>
}

<span class="hljs-meta">@Repository</span>
<span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">MyRepositoryImpl2</span> <span class="hljs-keyword">implements</span> <span class="hljs-title">MyRepository</span> </span>{
    <span class="hljs-comment">//implementation</span>
}
</code></pre>
<p>In this example, <code>MyRepositoryImpl1</code> will be used by default as it is annotated with <code>@Primary</code>.</p>
<p>The <code>@DependsOn</code> annotation can be used to specify that a particular bean should be initialized before another bean. For example, if we have a <code>MyService</code> class that depends on a <code>MyRepository</code> class and a <code>MyInitializer</code> class, we can use the <code>@DependsOn</code> annotation to ensure that the <code>MyInitializer</code> bean is initialized before the <code>MyRepository</code> bean:</p>
<pre><code class="lang-java"><span class="hljs-meta">@Service</span>
<span class="hljs-meta">@DependsOn("myInitializer")</span>
<span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">MyService</span> </span>{
    <span class="hljs-meta">@Autowired</span>
    <span class="hljs-keyword">private</span> MyRepository myRepository;
}

<span class="hljs-meta">@Component</span>
<span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">MyInitializer</span> </span>{
    <span class="hljs-comment">//initialization code</span>
}
</code></pre>
<p>In this example, the <code>MyInitializer</code> bean will be initialized before the <code>MyService</code> bean, ensuring that the <code>MyRepository</code> bean has access to any resources that may have been initialized by <code>MyInitializer</code>.</p>
<h3 id="heading-best-practices-1"><strong>Best Practices</strong></h3>
<ul>
<li><p>Use <code>@Lazy</code> to delay the initialization of a bean until it is actually needed.</p>
</li>
<li><p>Use <code>@Primary</code> to specify that a particular bean should be used by default when multiple beans of the same type are found.</p>
</li>
<li><p>Use <code>@DependsOn</code> to specify that a particular bean should be initialized before another bean.</p>
</li>
<li><p>Avoid creating circular references whenever possible.</p>
</li>
</ul>
<h2 id="heading-spring-bean-life-cycle"><strong>Spring Bean Life Cycle</strong></h2>
<p>The Spring Bean Life Cycle consists of several phases, including instantiation, dependency injection, initialization, and destruction. Understanding these phases and how to use annotations such as <code>@PostConstruct</code> and <code>@PreDestroy</code> can help you to write more efficient and effective code.</p>
<p>The <code>@PostConstruct</code> annotation can be used to indicate a method that should be called after the bean is constructed and all its dependencies have been injected. For example, if we have a <code>MyService</code> class that needs to perform some initialization after it has been constructed, we can use the <code>@PostConstruct</code> annotation on a method to achieve this:</p>
<pre><code class="lang-java"><span class="hljs-meta">@Service</span>
<span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">MyService</span> </span>{
    <span class="hljs-meta">@Autowired</span>
    <span class="hljs-keyword">private</span> MyRepository myRepository;

    <span class="hljs-meta">@PostConstruct</span>
    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">init</span><span class="hljs-params">()</span> </span>{
        <span class="hljs-comment">//initialization code</span>
    }
}
</code></pre>
<p>In this example, the <code>init()</code> method will be called after the <code>MyService</code> bean has been constructed and all its dependencies have been injected.</p>
<p>The <code>@PreDestroy</code> annotation can be used to indicate a method that should be called before the bean is destroyed. For example, if we have a <code>MyService</code> class that needs to perform some cleanup before it is destroyed, we can use the <code>@PreDestroy</code> annotation on a method to achieve this:</p>
<pre><code class="lang-java"><span class="hljs-meta">@Service</span>
<span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">MyService</span> </span>{
    <span class="hljs-meta">@Autowired</span>
    <span class="hljs-keyword">private</span> MyRepository myRepository;

    <span class="hljs-meta">@PreDestroy</span>
    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">cleanup</span><span class="hljs-params">()</span> </span>{
        <span class="hljs-comment">//cleanup code</span>
    }
}
</code></pre>
<p>In this example, the <code>cleanup()</code> method will be called before the <code>MyService</code> bean is destroyed.</p>
<p>It's also worth noting that Spring also provides other annotations for controlling the bean life cycle, such as <code>@Bean</code> and <code>@Scope</code>. The <code>@Bean</code> annotation is used to define a bean, while the <code>@Scope</code> annotation is used to define the scope of a bean (e.g. singleton, prototype, etc.).</p>
<h3 id="heading-best-practices-2"><strong>Best Practices</strong></h3>
<ul>
<li><p>Use <code>@PostConstruct</code> to indicate a method that should be called after the bean is constructed and all its dependencies have been injected.</p>
</li>
<li><p>Use <code>@PreDestroy</code> to indicate a method that should be called before the bean is destroyed.</p>
</li>
<li><p>Use <code>@Bean</code> and <code>@Scope</code> to control the bean life cycle.</p>
</li>
</ul>
<p>In conclusion, Dependency Injection, Circular References, and Spring Bean Life Cycle are all important concepts to understand when developing applications with Spring. By understanding these concepts and using the appropriate annotations, you can write more maintainable and testable code. Use these examples and best practices as a guide, and you'll be well on your way to mastering these topics.</p>
<p>The above article is an extensive guide on Dependency Injection, Circular References, and Spring Bean Life Cycle. It's a great resource for developers who want to learn more about these topics or want to improve their skills. The code examples in this article are in Java, but the concepts can be applied to other programming languages as well.</p>
]]></content:encoded></item><item><title><![CDATA[Getting Started with Spring Boot]]></title><description><![CDATA[This article is the first in a series of many related to the Springing into Action: A Spring Boot Journey from Novice to Pro Series, be sure to check out the series for more related content!
In this article, we will explore the benefits of using Spri...]]></description><link>https://amrtechuniverse.com/getting-started-with-spring-boot</link><guid isPermaLink="true">https://amrtechuniverse.com/getting-started-with-spring-boot</guid><category><![CDATA[Springboot]]></category><category><![CDATA[Web Development]]></category><category><![CDATA[Java]]></category><category><![CDATA[Spring]]></category><dc:creator><![CDATA[Amr Khaled]]></dc:creator><pubDate>Wed, 25 Jan 2023 11:11:32 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1674644740352/1bca7274-4d5a-40c9-a927-77e7946cd7cb.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>This article is the first in a series of many related to the <a target="_blank" href="https://amrtechuniverse.com/series/springboot-novice-to-pro">Springing into Action: A Spring Boot Journey from Novice to Pro</a> Series, be sure to check out the series for more related content!</p>
<p>In this article, we will explore the benefits of using Spring Boot, a widely-used Java framework, for building web applications. Spring Boot, which is built on top of the Spring framework, offers a range of convenient tools and features that allow for fast and efficient development. We will also delve into how to get started with using Spring Boot for your next project.</p>
<h2 id="heading-what-is-spring-boot">What is Spring Boot?</h2>
<p>Spring Boot is a framework for building web applications in Java. It is built on top of the Spring framework and provides a set of convenient tools and features for developing web applications quickly and efficiently. Some of the key features of Spring Boot include:</p>
<ul>
<li><p>Auto-configuration: Spring Boot automatically configures your application based on the dependencies you have included in your project. This means that you don't have to spend time manually configuring your application and can focus on writing your code.</p>
</li>
<li><p>Embedded web servers: Spring Boot includes an embedded web server, so you don't have to set up and configure a separate web server. This makes it easy to run your application locally and deploy it to a production environment.</p>
</li>
<li><p>Command-line interface: Spring Boot includes a command-line interface (CLI) that makes it easy to create new projects and run your application.</p>
</li>
</ul>
<h2 id="heading-getting-started">Getting Started</h2>
<p>To get started with Spring Boot, you will need to have the following tools installed on your machine:</p>
<ul>
<li><p>Java Development Kit (JDK) version 8 or later</p>
</li>
<li><p>Apache Maven</p>
</li>
</ul>
<p>Once you have the necessary tools installed, you can create a new Spring Boot project using the Spring Initializer. The Spring Initializer is a web-based tool that helps you create new Spring Boot projects. To use it, simply go to the <a target="_blank" href="https://start.spring.io/">Spring Initializer website</a> and select the options for your project.</p>
<p>Once you have created your project, you can open it in your favorite IDE and start developing your application.</p>
<h2 id="heading-creating-a-simple-rest-api">Creating a Simple REST API</h2>
<p>Now that you have a basic Spring Boot project set up, let's create a simple REST API. First, we need to add the <code>spring-web</code> dependency to our <code>pom.xml</code> file:</p>
<pre><code class="lang-xml"><span class="hljs-tag">&lt;<span class="hljs-name">dependency</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">groupId</span>&gt;</span>org.springframework.boot<span class="hljs-tag">&lt;/<span class="hljs-name">groupId</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">artifactId</span>&gt;</span>spring-boot-starter-web<span class="hljs-tag">&lt;/<span class="hljs-name">artifactId</span>&gt;</span>
<span class="hljs-tag">&lt;/<span class="hljs-name">dependency</span>&gt;</span>
</code></pre>
<p>Next, we will create a new class called <code>HelloController</code>:</p>
<pre><code class="lang-java"><span class="hljs-meta">@RestController</span>
<span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">HelloController</span> </span>{

    <span class="hljs-meta">@GetMapping("/hello")</span>
    <span class="hljs-function"><span class="hljs-keyword">public</span> String <span class="hljs-title">hello</span><span class="hljs-params">()</span> </span>{
        <span class="hljs-keyword">return</span> <span class="hljs-string">"Hello, Spring Boot!"</span>;
    }
}
</code></pre>
<p>This class is a simple REST controller that maps the <code>/hello</code> endpoint to the <code>hello()</code> method. When this endpoint is called, the method will return the string "Hello, Spring Boot!".</p>
<p>Now, we can start our application and test our endpoint using a tool like <code>curl</code> or <code>Postman</code>:</p>
<pre><code class="lang-java">curl http:<span class="hljs-comment">//localhost:8080/hello</span>
</code></pre>
<p>You should see the following output:</p>
<pre><code class="lang-java">Hello, Spring Boot!
</code></pre>
<h2 id="heading-why-use-spring-boot"><strong>Why Use Spring Boot?</strong></h2>
<p>Now that we've seen how easy it is to get started with Spring Boot and create a simple REST API, you may be wondering why you should use it for your next project. Here are a few reasons why:</p>
<ul>
<li><p>Productivity: Spring Boot makes it easy to create new projects and get started quickly. Its auto-configuration feature means that you don't have to spend time manually configuring your application and can focus on writing your code. This can significantly increase your productivity and help you get your application up and running faster.</p>
</li>
<li><p>Scalability: Spring Boot is built on top of the Spring framework, which is a well-established and widely-used framework for building Java applications. This means that it is highly scalable and can handle large and complex projects.</p>
</li>
<li><p>Flexibility: Spring Boot is highly configurable and allows you to choose the components and dependencies that you need for your project. This means that you can easily customize your application to meet your specific requirements.</p>
</li>
<li><p>Community: Spring Boot is an open-source framework with a large and active community. This means that there are many resources available to help you learn and use the framework, as well as a wide range of third-party libraries and modules that you can use to extend the functionality of your application.</p>
</li>
</ul>
<p>In conclusion, Spring Boot is an excellent choice for building web applications in Java. Its easy-to-use tools and features make it easy to get started and increase productivity, while its scalability, flexibility, and community support make it a great choice for large and complex projects. If you're looking for a framework to build your next web application, consider giving Spring Boot a try.</p>
]]></content:encoded></item><item><title><![CDATA[Intro To Python Programming]]></title><description><![CDATA[Hello and welcome to the latest blog in the Data Analysis, AI, Machine Learning and Everything In Between Series, today we will talk about python, how to install it, basic data types, conditionals & functions.

What Is Python?
Python is one of the mo...]]></description><link>https://amrtechuniverse.com/intro-to-python-programming</link><guid isPermaLink="true">https://amrtechuniverse.com/intro-to-python-programming</guid><category><![CDATA[Python 3]]></category><category><![CDATA[Python]]></category><category><![CDATA[python beginner]]></category><category><![CDATA[Tutorial]]></category><dc:creator><![CDATA[Amr Khaled]]></dc:creator><pubDate>Thu, 10 Mar 2022 20:24:55 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/unsplash/ieic5Tq8YMk/upload/v1646839409425/u-uD4a4Zi.jpeg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>Hello and welcome to the latest blog in the <a target="_blank" href="https://amrtechuniverse.com/series/data-basics">Data Analysis, AI, Machine Learning and Everything In Between</a> Series, today we will talk about python, how to install it, basic data types, conditionals &amp; functions.</p>
<hr />
<h2 id="heading-what-is-python">What Is Python?</h2>
<p>Python is one of the most widely used programming languages. Guido van Rossum created it, and it was released in 1991.</p>
<p>Python is a dynamically semantic, interpreted, object-oriented high-level programming language. Its high-level built-in data structures, together with dynamic typing and dynamic binding, making it ideal for Rapid Application Development and as a scripting or glue language for connecting existing components.</p>
<p>Python's concise, easy-to-learn syntax prioritizes readability, which lowers software maintenance costs. Modules and packages are supported by Python, which fosters program modularity and code reuse. The Python interpreter and its substantial standard library are free to download and distribute in source or binary form for all major platforms.</p>
<h2 id="heading-why-is-python-so-well-liked">Why is Python so well-liked?</h2>
<p>Python is widely used for a variety of purposes. Here's a closer look at what makes it so flexible and user-friendly for programmers.</p>
<ul>
<li><p>It features a straightforward syntax that resembles normal English, making it easier to read and comprehend. This speeds up the development of projects as well as the improvement of existing ones.</p>
</li>
<li><p>It's adaptable. Python can be used for a variety of purposes, including web development and machine learning.</p>
</li>
<li><p>It's user-friendly, making it popular among new programmers.</p>
</li>
<li><p>It's free to use and distribute, even for commercial purposes, because it's open source.</p>
</li>
<li><p>The Python module and library archive—bundles of code developed by third-party users to extend Python's capabilities—is large and growing.</p>
</li>
<li><p>Python has a vibrant community that contributes to the library of modules and libraries and serves as a resource for other programmers. Because of the large support network, finding a solution to a stumbling block is extremely simple; someone has almost certainly encountered the same issue before.</p>
</li>
</ul>
<h2 id="heading-install-python">Install Python</h2>
<p>There are various ways to install python, you can try to download it as a stand-alone from <a target="_blank" href="https://www.python.org/downloads/">Python's Official Website</a> or the most common way to install it with other Data science tools is through <a target="_blank" href="https://www.anaconda.com/">Anaconda</a></p>
<p>Anaconda is a Python and R programming language distribution aimed for simplifying package management and deployment in scientific computing (data science, machine learning applications, large-scale data processing, predictive analytics, and so on).</p>
<p>After you install Python you can run the following command to check that it was installed successfully:</p>
<pre><code>python <span class="hljs-operator">-</span><span class="hljs-operator">-</span>version
</code></pre><h2 id="heading-most-common-ides">Most Common IDEs</h2>
<p>There are a lot of IDEs which we can use to write Python programs, but the most commonly used ones - Not in a particular order- are as follows:</p>
<ul>
<li><p><a target="_blank" href="https://www.jetbrains.com/pycharm/">PyCharm</a></p>
</li>
<li><p><a target="_blank" href="https://code.visualstudio.com/">Visual Studio Code</a></p>
</li>
<li><p><a target="_blank" href="https://jupyter.org/install.html">Jupyter Notebook</a></p>
</li>
<li><p><a target="_blank" href="https://www.pydev.org/">PyDev</a></p>
</li>
<li><p><a target="_blank" href="https://www.tabnine.com/get">Tabnine</a></p>
</li>
<li><p><a target="_blank" href="https://atom.io/">Atom</a></p>
</li>
</ul>
<p><em>*Note</em>: Jupyter comes pre-installed with Anaconda *</p>
<h2 id="heading-getting-started-with-python">Getting Started With Python</h2>
<p>Python is an interpreted programming language, which means that you write Python (.py) files in a text editor before passing them to the Python interpreter to run.</p>
<p>On the command line, you can run a python script like follows:</p>
<pre><code>C:\Users\your <span class="hljs-type">name</span>&gt;python helloworld.py
</code></pre><p>The name of your python file should be "helloworld.py."</p>
<p>Let's begin by writing our first Python file, helloworld.py, in any text editor or IDE:</p>
<pre><code>print(<span class="hljs-string">"Hello, From Amr's Tech Universe Blog!"</span>)
</code></pre><p>The output should read:</p>
<pre><code>Hello, <span class="hljs-built_in">From</span> Amr<span class="hljs-symbol">'s</span> Tech Universe Blog!
</code></pre><h4 id="heading-indentation">Indentation</h4>
<p>Instead of curly braces, Python utilises indentation for blocks. Both tabs and spaces are supported, however normal Python code must utilize four spaces to be indented properly.</p>
<h4 id="heading-variables-andamp-types">Variables &amp; Types</h4>
<p>Python is an object-oriented programming language that is not "statically typed." You don't need to define variables or their types before utilizing them. In Python, every variable is an object.</p>
<h5 id="heading-commenting"><strong>Commenting</strong></h5>
<p>Comments are used to explain our code for others reading our code or for us so we don't forget what is done here</p>
<p>You can comment codes like this:</p>
<pre><code><span class="hljs-comment"># This is a single line comment</span>

<span class="hljs-string">"""
This is a multiline comment
in Python
"""</span>
</code></pre><h5 id="heading-variables"><strong>Variables</strong></h5>
<p>Variables are storage containers for data values. You can't declare a variable in Python like in strongly-typed languages; a variable is only created when you initially assign a value to a it</p>
<p>For example lets say that you want to define a variabl;e and assign the number 1997 to it,  you can do it like this: <code>myVar = 1997</code></p>
<p>now lets say that you changed your mind and want to store it as a string or a float even, In other languages you would have to define a new variable and cast the existing one to match the new variable's data type, but in Python you can do it as follows:</p>
<pre><code>myVar = <span class="hljs-number">1997</span>

<span class="hljs-comment"># Casting myVar to float:</span>
myVar = <span class="hljs-keyword">float</span>(myVar)
<span class="hljs-keyword">print</span>(myVar) <span class="hljs-comment"># 1997.0</span>

<span class="hljs-comment"># Returning myVar to int:</span>
myVar = <span class="hljs-keyword">int</span>(myVar) 
<span class="hljs-keyword">print</span>(myVar) <span class="hljs-comment"># 1997</span>

<span class="hljs-comment"># Casting myVar to string:</span>
myvar = str(myVar)
<span class="hljs-keyword">print</span>(myVar) <span class="hljs-comment"># "1997"</span>
</code></pre><p>Moreover, you can un-pack variable from a list, assign the same value to multiple variables and much more as we will show in the code example below:</p>
<pre><code><span class="hljs-comment"># Multiple assignments</span>
a, b, c = <span class="hljs-string">"Intro"</span>, <span class="hljs-string">"To"</span>, <span class="hljs-string">'Python'</span>

print(a)   <span class="hljs-comment"># "Intro"</span>
print(b)   <span class="hljs-comment"># "To"</span>
print(c)   <span class="hljs-comment"># "Python"</span>

<span class="hljs-comment"># one value to multiple variables assignment</span>
a, b, c = <span class="hljs-string">"Intro To Python"</span> <span class="hljs-comment"># or 'Intro To Python'</span>

print(a)   <span class="hljs-comment"># "Intro To Python"</span>
print(b)   <span class="hljs-comment"># "Intro To Python"</span>
print(c)   <span class="hljs-comment"># "Intro To Python"</span>

<span class="hljs-comment"># Unpacking lists</span>
groupOfWords = [<span class="hljs-string">"Intro"</span>, <span class="hljs-string">"To"</span>, <span class="hljs-string">"Python"</span>]
x, y, z = groupOfWords
print(x)   <span class="hljs-comment"># "Intro"</span>
print(y)   <span class="hljs-comment"># "To"</span>
print(z)   <span class="hljs-comment"># "Python"</span>
</code></pre><p>As you have seen, the variables in python are dynamic and change their type based on the value assigned to them as variables are treated like objects.</p>
<p>However, there are a few aspects to consider:</p>
<ul>
<li><p>Python is case-sensitive, so <code>MyVar</code> is different from <code>myVar</code></p>
</li>
<li><p>The name of a variable must begin with a letter or the underscore character</p>
</li>
<li><p>A number cannot be the first character in a variable name</p>
</li>
<li><p>String can be created with either <code>"</code> or <code>'</code>, the only difference is with <code>"</code> you can include apostrophes</p>
</li>
<li><p>The type() method can be used to return the data type of a variable </p>
</li>
</ul>
<h5 id="heading-built-in-data-types"><strong>Built-in-Data Types</strong></h5>
<p>Data type is a crucial notion in programming.
Variables can store a variety of data, and different types can perform different tasks.
Python comes with the following data types pre-installed in these categories:</p>
<ul>
<li>Text Type:    <code>str</code></li>
<li>Numeric Types:    <code>int</code>, <code>float</code>, <code>complex</code></li>
<li>Sequence Types:    <code>list</code>, <code>tuple</code>, <code>range</code></li>
<li>Mapping Type:     <code>dict</code></li>
<li>Set Types:    <code>set</code>, <code>frozenset</code></li>
<li>Boolean Type:     <code>bool</code></li>
<li>Binary Types:    <code>bytes</code>, <code>bytearray</code>, <code>memoryview</code></li>
</ul>
<h4 id="heading-lists">Lists</h4>
<p>As we have shown in the previous code example, arrays and lists are extremely similar. They can contain any sort of variable, as well as an unlimited number of variables. It is also possible to iterate across lists in a very simple method.</p>
<p>Lists are ordered, which means that any newly added items are inserted at the end by default. They can hold multiple data types at the same time and also allow duplicates.</p>
<p>Lets show some examples to better understand what was just saiud and explore some of Lists functionalities:</p>
<pre><code><span class="hljs-attribute">myList</span> =<span class="hljs-meta"> ["Amr", 25.0, 1997]</span>

<span class="hljs-comment"># Accessing items in list</span>
<span class="hljs-attribute">name</span>= myList[<span class="hljs-number">0</span>]    # <span class="hljs-string">"Amr"</span>
<span class="hljs-attribute">year</span>= myList[-<span class="hljs-number">1</span>] # Or myList[<span class="hljs-number">2</span>] or myList[len(names) - <span class="hljs-number">1</span>]

<span class="hljs-attribute">print</span>(myList)  # <span class="hljs-meta"> ["Amr", 25.0, 1997]</span>

<span class="hljs-comment"># Add new items</span>
<span class="hljs-attribute">myList</span>.append(<span class="hljs-string">"Hello"</span>) # Inserts at the end of List
<span class="hljs-attribute">myList</span>.Insert(<span class="hljs-number">0</span>, <span class="hljs-string">"New Item"</span>) # Inserts at the First position of the List

<span class="hljs-comment"># Modify Items</span>
<span class="hljs-attribute">myList</span>[<span class="hljs-number">1</span>] = <span class="hljs-string">"Second Item"</span>

<span class="hljs-attribute">print</span>(myList) # <span class="hljs-meta"> ["New Item" ,"Second Item", 25.0, 1997]</span>

<span class="hljs-comment"># Delete Items</span>
<span class="hljs-attribute">myList</span>.pop() # Removes the last item in List
<span class="hljs-attribute">myList</span>.remove(<span class="hljs-string">"Second Item"</span>)

<span class="hljs-attribute">print</span>(myList) # <span class="hljs-meta"> ["New Item" , 25.0]</span>

<span class="hljs-comment"># List Looping</span>
<span class="hljs-attribute">for</span> item in myList:
    <span class="hljs-attribute">print</span>(item) # {<span class="hljs-number">0</span>} -&gt; <span class="hljs-string">"New Item"</span>, {<span class="hljs-number">1</span>} -&gt; <span class="hljs-number">25</span>.<span class="hljs-number">0</span>

<span class="hljs-attribute">for</span> i in range(len(myList)):
    <span class="hljs-attribute">print</span>(myList[i]) # {<span class="hljs-number">0</span>} -&gt; <span class="hljs-string">"New Item"</span>, {<span class="hljs-number">1</span>} -&gt; <span class="hljs-number">25</span>.<span class="hljs-number">0</span>
</code></pre><h5 id="heading-list-comprehension"><strong>List Comprehension</strong></h5>
<p>Whenever you want to create a new list based on the values of an existing list, list comprehension has a shorter syntax.</p>
<p>Taking the list from the past example and applying list comprehension on it:</p>
<pre><code><span class="hljs-string">"""
Instead of looping on all items by our selves to print them,
we can do something like this:
"""</span>
[print(item) <span class="hljs-keyword">for</span> item <span class="hljs-keyword">in</span> myList] <span class="hljs-comment"># {0} -&gt; "New Item", {1} -&gt; 25.0</span>
</code></pre><h4 id="heading-tuples">Tuples</h4>
<p>Tuples are a type of variable that allows you to store several elements in a single variable.
A tuple is a collection of items that is both ordered and immutable.</p>
<p>Round brackets are used to write tuples. For example like GPS coordinates</p>
<pre><code><span class="hljs-attribute">egyptCoordinates</span> = (<span class="hljs-string">"26.8206° N"</span>, <span class="hljs-string">"30.8025° E"</span>)
<span class="hljs-attribute">print</span>(egyptCoordinates)  # ('<span class="hljs-number">26</span>.<span class="hljs-number">8206</span>° N', '<span class="hljs-number">30</span>.<span class="hljs-number">8025</span>° E')

<span class="hljs-comment"># Access Items</span>
<span class="hljs-attribute">print</span>(egyptCoordinates[<span class="hljs-number">0</span>])  # '<span class="hljs-number">26</span>.<span class="hljs-number">8206</span>° N'
</code></pre><p>We stated that tuples are <em>immutable</em>, but there is a workaround that can be done.
By casting the tuple to a list, it becomes mutable again and we can update its items then create a new tuple with the updated values.</p>
<pre><code><span class="hljs-attribute">myTuple</span> = (<span class="hljs-string">"Intro"</span>, <span class="hljs-string">"To"</span>, <span class="hljs-string">"Python"</span>)
<span class="hljs-attribute">myList</span> = list(myTuple)
<span class="hljs-attribute">myList</span>[<span class="hljs-number">1</span>] = <span class="hljs-number">0</span>.<span class="hljs-number">0</span>
<span class="hljs-attribute">myList</span>.append(<span class="hljs-number">5</span>)
<span class="hljs-attribute">myTuple</span> = tuple(myList)

<span class="hljs-attribute">print</span>(myTuple)  # ('Intro', <span class="hljs-number">0</span>.<span class="hljs-number">0</span>, 'Python', <span class="hljs-number">5</span>)
</code></pre><p>If we want to assign all tuple values to variables as we did with lists, we can do as below:</p>
<pre><code><span class="hljs-comment"># If number of variables is the same as items</span>
fruits = (<span class="hljs-string">"apple"</span>, <span class="hljs-string">"banana"</span>, <span class="hljs-string">"cherry"</span>)

(green, yellow, red) = fruits

<span class="hljs-comment"># If number of variables doesn't match the items</span>
fruits = (<span class="hljs-string">"apple"</span>, <span class="hljs-string">"banana"</span>, <span class="hljs-string">"cherry"</span>, <span class="hljs-string">"strawberry"</span>, <span class="hljs-string">"raspberry"</span>)

(green, yellow, *red) = fruits
</code></pre><p>Note the use of <code>*</code> before the variable <code>red</code>, It is used to assign the excess items to the latest variable in the form of a list.</p>
<h4 id="heading-dictionaries">Dictionaries</h4>
<p>Dictionaries are used to store data values in key:value pairs, they are mutable and don't allow duplicates in keys.</p>
<p>We will explore how to create, modify &amp; delete dictionaries in the code example below:</p>
<pre><code>person = {
  "name": "Amr Khaled",
  "gender": "Male",
  "age": <span class="hljs-number">25.0</span>,
  "occupation":{
   "company": "CIT VeriCash",
   "position": "Software Engineer"}
}

# <span class="hljs-keyword">Access</span> <span class="hljs-keyword">Values</span>
print(person["occupation"])  # {<span class="hljs-string">'company'</span>: <span class="hljs-string">'CIT VeriCash'</span>, <span class="hljs-string">'position'</span>: <span class="hljs-string">'Software Engineer'</span>}
</code></pre><p>The process of adding or modifying dictionaries is practically the same.
If a key exists then it will be added, but if it is found then its value is updated</p>
<pre><code># Adding a <span class="hljs-built_in">new</span> Key-<span class="hljs-keyword">Value</span> Pair
person["hasCar"] = <span class="hljs-keyword">True</span>

print(person) # {<span class="hljs-string">'name'</span>: <span class="hljs-string">'Amr Khaled'</span>, <span class="hljs-string">'gender'</span>: <span class="hljs-string">'Male'</span>, <span class="hljs-string">'age'</span>: <span class="hljs-number">25.0</span>, <span class="hljs-string">'occupation'</span>: {<span class="hljs-string">'company'</span>: <span class="hljs-string">'CIT VeriCash'</span>, <span class="hljs-string">'position'</span>: <span class="hljs-string">'Software Engineer'</span>}, <span class="hljs-string">'hasCar'</span>: <span class="hljs-keyword">True</span>}

# Modifying a <span class="hljs-built_in">new</span> Key-<span class="hljs-keyword">Value</span> Pair
person["hasCar"] = <span class="hljs-keyword">False</span>

print(person) # {<span class="hljs-string">'name'</span>: <span class="hljs-string">'Amr Khaled'</span>, <span class="hljs-string">'gender'</span>: <span class="hljs-string">'Male'</span>, <span class="hljs-string">'age'</span>: <span class="hljs-number">25.0</span>, <span class="hljs-string">'occupation'</span>: {<span class="hljs-string">'company'</span>: <span class="hljs-string">'CIT VeriCash'</span>, <span class="hljs-string">'position'</span>: <span class="hljs-string">'Software Engineer'</span>}, <span class="hljs-string">'hasCar'</span>: <span class="hljs-keyword">False</span>}
</code></pre><h4 id="heading-loops-andamp-conditionals">Loops &amp; Conditionals</h4>
<p>Loops come in a variety of forms, and they're used to iterate over data and apply logic before moving on to the next item or returning a specific item.</p>
<p>They are often used in conjunction with logical conditionals and <code>if ... else</code> statements, that we will discuss shortly</p>
<h5 id="heading-for-loops"><strong>For Loops</strong></h5>
<pre><code><span class="hljs-comment"># Loop over a string</span>
<span class="hljs-keyword">for</span> x <span class="hljs-keyword">in</span> <span class="hljs-string">"banana"</span>:
  print(x)   <span class="hljs-comment"># {0} -&gt; 'b', {1} -&gt; 'a', ......, {5} -&gt;'a'</span>

<span class="hljs-comment"># Loop over a list</span>
<span class="hljs-keyword">for</span> x <span class="hljs-keyword">in</span> [<span class="hljs-string">"Intro"</span>, <span class="hljs-string">"To"</span>, <span class="hljs-string">"Python"</span>]
  print(x)  <span class="hljs-comment"># {0} -&gt; 'Intro', {1} -&gt; 'To', {2} -&gt; 'Python'</span>

<span class="hljs-comment"># Loop over a range</span>
<span class="hljs-keyword">for</span> x <span class="hljs-keyword">in</span> range(<span class="hljs-number">20</span>):
  print(x)  <span class="hljs-comment">#  {0} -&gt; 0, {1} -&gt; 1, ......, {19} -&gt; 19</span>

<span class="hljs-comment"># Using Break statement</span>
fruits = [<span class="hljs-string">"apple"</span>, <span class="hljs-string">"banana"</span>, <span class="hljs-string">"cherry"</span>]
<span class="hljs-keyword">for</span> x <span class="hljs-keyword">in</span> fruits:
  <span class="hljs-keyword">if</span> x == <span class="hljs-string">"banana"</span>:
    <span class="hljs-keyword">break</span> <span class="hljs-comment"># used to stop the for loop and resume the code execution</span>

<span class="hljs-comment"># Using Continue Statement</span>
fruits = [<span class="hljs-string">"apple"</span>, <span class="hljs-string">"banana"</span>, <span class="hljs-string">"cherry"</span>]
<span class="hljs-keyword">for</span> x <span class="hljs-keyword">in</span> fruits:
  <span class="hljs-keyword">if</span> x == <span class="hljs-string">"banana"</span>:
    <span class="hljs-keyword">continue</span>  <span class="hljs-comment"># Skip the rest of the code in this iteration of loop and start with the next index</span>
</code></pre><h5 id="heading-while-loops"><strong>While Loops</strong></h5>
<p>We can use the while loop to run a series of statements as long as a condition is true.</p>
<pre><code><span class="hljs-comment"># Print all numbers less than x</span>
x = <span class="hljs-number">100</span>
i = <span class="hljs-number">0</span>
<span class="hljs-keyword">while</span> i &lt; x:
  print(i)
  i += <span class="hljs-number">1</span>
<span class="hljs-keyword">else</span>:
  print(<span class="hljs-string">"i = x"</span>)
</code></pre><h5 id="heading-if-statements"><strong>If Statements</strong></h5>
<p>Assume that we are at a party and we are responsible for handling door access, we have to set some ground rules as to who will we allow to our party, maybe we want people to be above 21 or if they are on the invitation list, then we can allow them to enter, but how do we translate that to python code? Lets see, shall we?</p>
<pre><code>minimumAge = 21
invitedPeopleList = [<span class="hljs-string">"Amr"</span>, <span class="hljs-string">"Maryam"</span>, <span class="hljs-string">"Anas"</span>, <span class="hljs-string">"Habiba"</span>, <span class="hljs-string">"Merna"</span>, <span class="hljs-string">"Nada"</span>, <span class="hljs-string">"Ayman"</span>, <span class="hljs-string">"May"</span>]

person = {<span class="hljs-string">"name"</span>: <span class="hljs-string">"Ahmed"</span>, <span class="hljs-string">"age"</span>: 19}

isAllowedEntry = False <span class="hljs-comment"># Initially everyone is denied entry</span>

if person[<span class="hljs-string">"name"</span>] in invitedPeopleList or person[<span class="hljs-string">"age"</span>] &gt;= minimumAge:
    isAllowedEntry = True
<span class="hljs-section">else:</span>
    isAllowedEntry = False
</code></pre><p><em>*Note</em>: The <code>else</code> statement above is redundant but was included for clarification purposes *</p>
<h4 id="heading-functions">Functions</h4>
<p>A function is a piece of code that only runs when it is invoked. It accepts data in the form of parameters and as a result of its operation, a function can return data in the form of one variable or more.</p>
<p>If we want to create a function that takes two integers as input and outputs a bunch of arithmetic operations - sum, multiplication, difference, reminder &amp; power - </p>
<p>We can group all of those operations into a function and implement it as follows:</p>
<pre><code><span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">getArithmeticOperations</span>(<span class="hljs-params">x, y</span>):</span>
    sum = x+y
    diff = x-y
    multi = x*y
    power=x**y
    rem = x%y

    <span class="hljs-keyword">return</span> sum, diff, multi, power, rem

a = <span class="hljs-number">10</span>
b = <span class="hljs-number">2</span>

sum, diff, multi, power, rem = getArithmeticOperations(a,b)

print(sum)  <span class="hljs-comment"># 12</span>
print(diff)   <span class="hljs-comment"># 8</span>
print(multi)  <span class="hljs-comment"># 20</span>
print(power)  <span class="hljs-comment"># 100</span>
print(rem)   <span class="hljs-comment"># 0</span>
</code></pre><hr />
<p>Wow! that was a lot. If you are still feeling fuzzy or don't know how to memorize all of this new information, it is perfectly okay.</p>
<p>Remember that Rome, was not built in a day and that practice makes perfect.
Try and familiarize yourself with more python syntax and problems and you will surely be on your way!</p>
<p>In this tutorial, I tried to give you the basics that I wished someone had told me about when I started my coding journey, this is just an introduction so you and I still have a long way to go together. But we all have to start somewhere.</p>
<hr />
<p>Thank you so much for reading, hope you enjoyed it as much as I enjoyed writing it!
See you soon with more blogs &amp; tutorials in our <a target="_blank" href="https://amrtechuniverse.com/series/data-basics">Data Analysis, AI, Machine Learning and Everything In Between</a> Series</p>
]]></content:encoded></item><item><title><![CDATA[How to - Data Analysis With SQL]]></title><description><![CDATA[Are you a Data Enthusiast? Do you want to learn more about Data Analysis & SQL?
Then you have come to the right place! In this blog you will be introduced to practical Data Analysis using SQL, and we will get to dive deeper into SQL and continue our ...]]></description><link>https://amrtechuniverse.com/how-to-data-analysis-with-sql</link><guid isPermaLink="true">https://amrtechuniverse.com/how-to-data-analysis-with-sql</guid><category><![CDATA[SQL]]></category><category><![CDATA[Data Science]]></category><category><![CDATA[Databases]]></category><category><![CDATA[data analysis]]></category><category><![CDATA[Beginner Developers]]></category><dc:creator><![CDATA[Amr Khaled]]></dc:creator><pubDate>Tue, 08 Mar 2022 18:48:04 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/unsplash/IKHvOlZFCOg/upload/v1646731854214/8WUQomUcp.jpeg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>Are you a Data Enthusiast? Do you want to learn more about Data Analysis &amp; SQL?</p>
<p>Then you have come to the right place! In this blog you will be introduced to practical Data Analysis using SQL, and we will get to dive deeper into SQL and continue our previous SQL tutorial, If you haven't already then please go check <a target="_blank" href="https://amrtechuniverse.com/how-i-met-your-database-and-mainly-relational-using-sql">How I Met Your Database -&amp; Mainly Relational Using SQL-</a></p>
<hr />
<h2 id="heading-northwind-database">Northwind Database</h2>
<p>In this blog, we will be working with <a target="_blank" href="https://docs.yugabyte.com/latest/sample-data/northwind/">Northwind Database</a>, which is a sample database created by Microsoft to practice fictional data in a company environment.</p>
<p>The database consists of the following tables:</p>
<ul>
<li><p>Suppliers: Suppliers and vendors of Northwind</p>
</li>
<li><p>Customers: Customers who buy products from Northwind</p>
</li>
<li><p>Employees: Employee details of Northwind traders</p>
</li>
<li><p>Products: Product information</p>
</li>
<li><p>Shippers: The names and contact information for the shippers who transport the goods from the traders to the end-users.</p>
</li>
<li><p>Orders and Order_Details: Customers' and the companies' sales order interactions.</p>
</li>
</ul>
<p>To have a broader idea of the database structure, we can check the below Entity Relationship Diagram -ERD-:</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1646737268535/yryzf6itV.png" alt="Northwind ERD.png" />
<em>*Image credits goes to: <a target="_blank" href="https://docs.yugabyte.com">yugabyte</a></em> *</p>
<hr />
<h2 id="heading-the-power-of-sql-queries">The Power Of SQL Queries</h2>
<p>You now have a database that is completely ready for you to explore, so let's start by utilizing SQL and asking ourselves, what insights can we gain from our Database ?</p>
<h3 id="heading-highest-performing-employees">Highest Performing Employees</h3>
<p>Let's say that we measure our performance goals solely on the volume of orders, regardless of their monetary value.</p>
<p>We can use our SQL knowledge to know who the highest performing employees based on number of orders.</p>
<p>Based on the ERD above, the reference that links - Foreign Key -  between the Orders &amp; the Employees Tables is the Employee ID.</p>
<h4 id="heading-foreign-keys"><strong>Foreign Keys</strong></h4>
<p>A <code>FOREIGN KEY</code> is a field (or set of fields) in one table that points to a <code>PRIMARY KEY</code> in another table.
The child table is the table with the foreign key, and the referred or parent table is the table with the primary key.</p>
<h4 id="heading-sql-query"><strong>SQL Query</strong></h4>
<p>The Query to get the volume of orders and the employee responsible looks like this:</p>
<pre><code>SELECT E.EmployeeID As Employee_ID, 
COUNT(O.EmployeeID) AS Order_Count, 
CONCAT(E.FirstName, <span class="hljs-string">' '</span> ,E.LastName) As Full_Name
FROM Orders <span class="hljs-keyword">as</span> O
inner join Employees <span class="hljs-keyword">as</span> E on O.EmployeeID <span class="hljs-operator">=</span> E.EmployeeID
group by E.EmployeeID, E.FirstName, E.LastName;
</code></pre><p>Lets dissect the query and understand what each part does, starting with <code>GROUP BY</code></p>
<h5 id="heading-group-by"><strong><em>GROUP BY</em></strong></h5>
<p>The <code>GROUP BY</code> statement is used to groups rows with the same values into summary rows. </p>
<p>To group the result set by one or more columns, the <code>GROUP BY</code> statement is frequently used with aggregate functions (COUNT(), MAX(), MIN(), SUM(), AVG()). </p>
<p>In the above query however we can see that we grouped by The Employee's ID, First Name &amp; Last Name.</p>
<h5 id="heading-aliases"><strong><em>Aliases</em></strong></h5>
<p>SQL aliases are used to give a table, or a column in a table, a temporary name, they are often used to make column names more readable.</p>
<p>An alias only exists for the duration of that query and is created with the <code>AS</code> keyword.</p>
<h5 id="heading-inner-join"><strong><em> Inner Join</em></strong></h5>
<p>The <code>INNER JOIN</code> keyword picks records in both tables that have the same value.
You can think about <code>Inner Join</code> in the term of the intersection between two tables</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1646756546135/UYoYdj3a2.png" alt="Inner Join Two Tables" /></p>
<p>If the columns in both tables match, the INNER JOIN keyword selects all rows from both tables. These orders will not be displayed if there are records in the "Orders" table that do not have matches in the "Employees" table!</p>
<p>There are a lot of table join types, we will discuss them as the need arises but you can check the below Venn Diagram as it will provide you with a brief explanation for the use-case of each join type:</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1646756839091/1Z6ZNkSNx.jpg" alt="SQL_Joins.jpg" /></p>
<h4 id="heading-query-output"><strong><em>Query Output</em></strong></h4>
<p>Our executed query will yield the following result -as shown below- and this provided us with insight on which employees created the most orders for the customers.</p>
<pre><code><span class="hljs-string">Employee_ID</span>    <span class="hljs-string">Order_Count</span>     <span class="hljs-string">Full_Name</span>
    <span class="hljs-number">1</span>              <span class="hljs-number">123</span>        <span class="hljs-string">Nancy</span> <span class="hljs-string">Davolio</span>
    <span class="hljs-number">2</span>               <span class="hljs-number">96</span>        <span class="hljs-string">Andrew</span> <span class="hljs-string">Fuller</span>
    <span class="hljs-number">3</span>              <span class="hljs-number">127</span>        <span class="hljs-string">Janet</span> <span class="hljs-string">Leverling</span>
    <span class="hljs-number">4</span>              <span class="hljs-number">156</span>        <span class="hljs-string">Margaret</span> <span class="hljs-string">Peacock</span>
    <span class="hljs-number">5</span>               <span class="hljs-number">42</span>        <span class="hljs-string">Steven</span> <span class="hljs-string">Buchanan</span>
    <span class="hljs-number">6</span>               <span class="hljs-number">67</span>        <span class="hljs-string">Michael</span> <span class="hljs-string">Suyama</span>
    <span class="hljs-number">7</span>               <span class="hljs-number">72</span>        <span class="hljs-string">Robert</span> <span class="hljs-string">King</span>
    <span class="hljs-number">8</span>              <span class="hljs-number">104</span>        <span class="hljs-string">Laura</span> <span class="hljs-string">Callahan</span>
    <span class="hljs-number">9</span>               <span class="hljs-number">43</span>        <span class="hljs-string">Anne</span> <span class="hljs-string">Dodsworth</span>
</code></pre><p>But this is still missing something fundamental, did you notice it?</p>
<p>If your answer was their order then you are absolutely correct!, our query didn't order the elements based on volume of orders, it is still missing the <code>ORDER BY</code> clause.</p>
<h5 id="heading-order-by"><strong><em>ORDER BY</em></strong></h5>
<p>As the name suggests, if we want to sort the result set in ascending or descending order, use the ORDER BY keyword.</p>
<p>By default, the ORDER BY keyword organizes the records in ascending order. Use the DESC keyword to sort the records in descending order.</p>
<p>For example, In our query, we should add the <code>order by</code> clause after the <code>group by</code> like this:</p>
<pre><code><span class="hljs-keyword">ORDER</span> <span class="hljs-keyword">BY</span> COUNT(O.EmployeeID) <span class="hljs-keyword">DESC</span>;

<span class="hljs-keyword">OR</span>

<span class="hljs-comment">-- Since we defined Order_Count as an Alias for COUNT(O.EmployeeID)</span>
<span class="hljs-comment">-- we can use them interchangeably</span>
<span class="hljs-keyword">order</span> <span class="hljs-keyword">by</span> Order_Count <span class="hljs-keyword">desc</span>;
</code></pre><p>And that yeilds the result set organized as below:</p>
<pre><code><span class="hljs-string">Employee_ID</span>    <span class="hljs-string">Order_Count</span>     <span class="hljs-string">Full_Name</span>
    <span class="hljs-number">4</span>              <span class="hljs-number">156</span>        <span class="hljs-string">Margaret</span> <span class="hljs-string">Peacock</span>
    <span class="hljs-number">3</span>              <span class="hljs-number">127</span>        <span class="hljs-string">Janet</span> <span class="hljs-string">Leverling</span>
    <span class="hljs-number">1</span>              <span class="hljs-number">123</span>        <span class="hljs-string">Nancy</span> <span class="hljs-string">Davolio</span>
    <span class="hljs-number">8</span>              <span class="hljs-number">104</span>        <span class="hljs-string">Laura</span> <span class="hljs-string">Callahan</span>
    <span class="hljs-number">2</span>               <span class="hljs-number">96</span>        <span class="hljs-string">Andrew</span> <span class="hljs-string">Fuller</span>
    <span class="hljs-number">7</span>               <span class="hljs-number">72</span>        <span class="hljs-string">Robert</span> <span class="hljs-string">King</span>
    <span class="hljs-number">6</span>               <span class="hljs-number">67</span>        <span class="hljs-string">Michael</span> <span class="hljs-string">Suyama</span>
    <span class="hljs-number">9</span>               <span class="hljs-number">43</span>        <span class="hljs-string">Anne</span> <span class="hljs-string">Dodsworth</span>
    <span class="hljs-number">5</span>               <span class="hljs-number">42</span>        <span class="hljs-string">Steven</span> <span class="hljs-string">Buchanan</span>
</code></pre><h3 id="heading-how-have-discounts-affected-the-number-of-items-sold">How have discounts affected the number of items sold?</h3>
<p>It is a known fact that we all LOVE sales, no matter what the sale is on, we lways manage to find something that we like and buy something new or an even larger quantity of something that we use on a regular basis.</p>
<p>But, this is not a scientific way to prove it, so how can we ?</p>
<p>We can start by getting the number of items sold with a sale and those sold without while comparing them with the number of orders made.</p>
<p>Let's see how we can achieve that with SQL.</p>
<h4 id="heading-sql-queries">SQL Queries</h4>
<p>We will be keeping the Queries simple and using only the basic syntax, but I strongly advice you to start reading about <code>Left Join</code> and joins in general and to start experimenting by yourself on various databases and datasets like <a target="_blank" href="https://www.kaggle.com/c/titanic">The Famous Titanic Dataset on Kaggle</a></p>
<p>The below queries check for the total number of items purchased and the number of orders made.</p>
<pre><code><span class="hljs-comment">-- For Items With Discounts:</span>

<span class="hljs-keyword">SELECT</span> <span class="hljs-keyword">SUM</span>(OD.Quantity) <span class="hljs-keyword">AS</span> Total_Items_Sold, <span class="hljs-keyword">Count</span>(OD.OrderID)
<span class="hljs-keyword">FROM</span> [<span class="hljs-keyword">Order</span> Details] <span class="hljs-keyword">as</span> OD
<span class="hljs-keyword">WHERE</span> OD.Discount &gt; <span class="hljs-number">0</span>;



<span class="hljs-comment">-- For Items Without Discounts:</span>

<span class="hljs-keyword">SELECT</span> <span class="hljs-keyword">SUM</span>(OD.Quantity) <span class="hljs-keyword">AS</span> Total_Items_Sold, <span class="hljs-keyword">Count</span>(OD.OrderID)
<span class="hljs-keyword">FROM</span> [<span class="hljs-keyword">Order</span> Details] <span class="hljs-keyword">as</span> OD
<span class="hljs-keyword">WHERE</span> OD.Discount = <span class="hljs-number">0</span>;
</code></pre><p>For the Results:</p>
<ul>
<li><p>Items With Discounts: A total of <code>22718</code> items were sold in <code>838</code> orders. </p>
<pre><code><span class="hljs-string">Total_Items_Sold</span>    <span class="hljs-string">Number_Of_Orders</span>
      <span class="hljs-number">22718</span>               <span class="hljs-number">838</span>
</code></pre></li>
<li><p>Items Without Discounts: A total of <code>28599</code> items in <code>1317</code> orders</p>
<pre><code><span class="hljs-string">Total_Items_Sold</span>    <span class="hljs-string">Number_Of_Orders</span>
      <span class="hljs-number">28599</span>               <span class="hljs-number">1317</span>
</code></pre></li>
</ul>
<p>If we calculate the <em>average number of items per order</em>, We will find that clearly the number of items purchased increases when a sale is present.</p>
<h3 id="heading-what-discount-percentage-should-the-company-offer">What discount percentage should the company offer?</h3>
<p>Now that we have seen that discounts affect the volume of our sales, we have to determine the best percentage that will help us maximize our profit &amp; market share.</p>
<p>Let's check the increments of 5% discounts in our database and see what our data is trying to tell us.</p>
<h4 id="heading-sql-query">SQL QUERY</h4>
<pre><code>SELECT SUM(OD.Quantity) AS Total_Items_Sold, Count(OD.OrderID)AS Number_Of_Orders, OD.Discount AS Discount_Percentage
FROM [Order Details] <span class="hljs-keyword">as</span> OD
WHERE OD.Discount <span class="hljs-operator">=</span> <span class="hljs-number">0</span><span class="hljs-number">.05</span> or OD.Discount <span class="hljs-operator">=</span><span class="hljs-number">0</span><span class="hljs-number">.1</span> or OD.Discount <span class="hljs-operator">=</span><span class="hljs-number">0</span><span class="hljs-number">.2</span> or OD.Discount <span class="hljs-operator">=</span><span class="hljs-number">0</span><span class="hljs-number">.25</span>
GROUP BY OD.Discount
ORDER BY OD.Discount DESC;
</code></pre><p>This shows the following results, which surprisingly show a very little change in the order sizes and numbers is an indicator for the Northwind company that if the offer a discount as low as <strong><em>5%</em></strong> , they will notice an increase in sales with no need to decrease their revenue any further.</p>
<pre><code><span class="hljs-attribute">Total_Items_Sold</span>    Number_Of_Orders    Discount_Percentage
      <span class="hljs-attribute">4349</span>                <span class="hljs-number">154</span>                  <span class="hljs-number">0</span>.<span class="hljs-number">25</span>
      <span class="hljs-attribute">4351</span>                <span class="hljs-number">161</span>                  <span class="hljs-number">0</span>.<span class="hljs-number">2</span>
      <span class="hljs-attribute">4366</span>                <span class="hljs-number">173</span>                  <span class="hljs-number">0</span>.<span class="hljs-number">1</span>
      <span class="hljs-attribute">5182</span>                <span class="hljs-number">185</span>                  <span class="hljs-number">0</span>.<span class="hljs-number">05</span>
</code></pre><p>We can take this even a step further and see the effect of discounts on different product categories or If discounts affect certain regions more than others, but I will leave that for you to answer and test your skills.</p>
<hr />
<p>This brings us to the end of today's blog about using SQL for Data Analysis, In the upcoming blog we will be getting to know Python and later on we will create a mini project with full code examples to handle the Northwind Database and other various datasets.</p>
<p>Hope you enjoyed reading this blog as much as I enjoyed writing it. If you have any comments or suggestions, please feel free to reach out ❤</p>
]]></content:encoded></item><item><title><![CDATA[Infrastructure as Code - An Introduction]]></title><description><![CDATA[Managing IT infrastructure used to be a difficult task. All of the hardware and software required for the programmes to run had to be manually managed and configured by system administrators.
However, things have altered considerably in recent years....]]></description><link>https://amrtechuniverse.com/infrastructure-as-code</link><guid isPermaLink="true">https://amrtechuniverse.com/infrastructure-as-code</guid><category><![CDATA[infrastructure]]></category><category><![CDATA[Beginner Developers]]></category><dc:creator><![CDATA[Amr Khaled]]></dc:creator><pubDate>Thu, 03 Mar 2022 16:56:55 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/unsplash/uAWRPtZ6n0s/upload/v1646300116660/hR5IajEVj.jpeg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>Managing IT infrastructure used to be a difficult task. All of the hardware and software required for the programmes to run had to be manually managed and configured by system administrators.</p>
<p>However, things have altered considerably in recent years. Cloud computing has transformed and improved the way businesses plan, create, and sustain their IT infrastructure.</p>
<p>One of the most important aspects of this paradigm is <strong><em>Infrastructure as Code</em></strong> and that's what we'll explore today.</p>
<hr />
<h3 id="heading-what-is-infrastructure-as-code">What Is Infrastructure as Code?</h3>
<p>Infrastructure as Code (IaC) refers to the process of managing and supplying infrastructure using code rather than manual methods. It is a descriptive approach for managing infrastructure (networks, virtual machines, load balancers, and connection topologies) that employs the same versioning as the DevOps team does for source code.</p>
<p>An IaC model generates the same environment every time it is applied, similar to the principle that the same source code generates the same binary; with configuration files containing your infrastructure specifications created with IaC, making it easier to change and distribute configurations.</p>
<h3 id="heading-why-use-iac">Why use IaC?</h3>
<p>Now that the "<em>what</em>" is out of the way, lets focus on why do we want to utilize Iac and what is its competitive advantage.</p>
<p>Infrastructure administration and configuration were formerly done manually. Each environment has its own unique configuration that was set up by hand, and that resulted in a number of issues, including:</p>
<ul>
<li><p>Cost: You'll need to pay a lot of people to manage and maintain the infrastructure.</p>
</li>
<li><p>Scaling: It takes time since it requires manual configuration of infrastructure operations, and that makes it difficult to handle surges in demand.</p>
</li>
<li><p>Inconsistency: Human infrastructure configuration is prone to errors, there is inconsistency. Errors are unavoidable when multiple individuals configure different environments.</p>
</li>
</ul>
<p>Whereas through IaC, you can achieve the following:</p>
<ul>
<li><p>Speed &amp; Simplicity: IaC delivers the full infrastructure with the click of a button by just running a script.</p>
</li>
<li><p>Consistency: All of it is specified as a code, which results in less errors than manual configuration.</p>
</li>
<li><p>Risk minimization: It enables a larger group of individuals to collaborate more effectively on infrastructure configuration and administration.</p>
</li>
<li><p>Cost Minimization: It will allow you to spend less time on routine infrastructure deployment activities and more time on more valuable tasks.</p>
</li>
<li><p>Reusability: It improves reusability with minimal adjustments.</p>
</li>
<li><p>Process Automation: As part of the continuous delivery process, it enables for the automation of the entire process from setup to removal.</p>
</li>
</ul>
<p>Furthermore, describing infrastructure as code entails the following:</p>
<ol>
<li><p>Allows infrastructure to be readily linked into version control techniques, making infrastructure modifications trackable and auditable.</p>
</li>
<li><p>Provides the ability to automate infrastructure management to a large extent. As a result of all of this, IaC is being integrated into CI/CD pipelines as a key component of the Software Development Life Cycle (SDLC).</p>
</li>
<li><p>Manual infrastructure provisioning and administration is no longer necessary. As a result, users can simply manage the underlying infrastructure's and configurations' unavoidable config drift while keeping all environments inside the intended configuration.</p>
</li>
</ol>
<h3 id="heading-challenges-of-iac">Challenges of IaC</h3>
<p>Each new approach introduces a new set of issues, and IaC is no exception. The same characteristics that make IaC so effective and efficient also provide enterprises with some unique problems. Here's a quick rundown of what they're all about:</p>
<h4 id="heading-accidental-destruction"><strong>Accidental Destruction</strong></h4>
<p>In theory, once automated systems are up and running, they don't require ongoing supervision beyond periodic maintenance and replacement. In truth, even automated systems have issues, and these issues can build up over time to become major system-level disasters. It's also known as erosion in technical terms.</p>
<h4 id="heading-configuration-drift"><strong>Configuration Drift</strong></h4>
<p>Automated configuration frequently results in infrastructure parts wandering over time. A repair applied to one server, for example, may not be reproduced across all servers. Although differences aren't necessarily negative, they must be documented and managed.</p>
<h4 id="heading-lack-of-expertise"><strong>Lack of Expertise</strong></h4>
<p>Creating definition files and testing them to verify that they perform properly necessitates a thorough understanding of the organization's IT architecture. That's a unique set of abilities.</p>
<h4 id="heading-lack-of-proper-design-andamp-planning"><strong>Lack of Proper Design &amp; Planning</strong></h4>
<p>Many unknowns surround automation projects, so it's critical to identify and address them early on in the planning process. Continuous testing and phased execution of automation projects can provide sceptics with the information and confidence they need to lead more automation projects in the future.</p>
<h4 id="heading-error-replication"><strong>Error Replication</strong></h4>
<p>It's simple to trace human actions and duplicate errors in manual operations. Error replication becomes a difficult problem when automation is involved. System administrators may not be able to correctly replicate error scenarios by analyzing log files, workflows, and other data.</p>
<hr />
<h3 id="heading-principles-of-iac">Principles of IaC</h3>
<h4 id="heading-1-easy-system-reproducibility"><strong>1. Easy System Reproducibility</strong></h4>
<p>Your IaC approach should make it simple and quick to create and rebuild any part of your IT infrastructure. They shouldn't necessitate a lot of human work or complicated decision-making.</p>
<p>All of the tasks involved must be coded into the definition files, from selecting the software through configuring it. The scripts and tools that handle resource provisioning should have enough data to complete their duties without the need for human intervention.</p>
<h4 id="heading-2-idempotence"><strong>2. Idempotence</strong></h4>
<p>Automated systems and their ability to handle difficult tasks are naturally viewed with suspicion by meticulous corporate leaders. As a result, no matter how many times IaC is run, it must maintain consistency. When new servers are installed, for example, they must be equal (or nearly identical) in capacity, performance, and dependability to the existing servers. This way, anytime new infrastructure parts are added, all decisions are automated and preset, from configuration to hosting names.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1646322802237/lIqTSSw59.png" alt="Idempotent VS Non-Idempotent" />
<em>*Photo Credit: https://shahadarsh.com/</em> *</p>
<h4 id="heading-3-repeatable-processes"><strong>3. Repeatable Processes</strong></h4>
<p>System administrators have a natural predilection towards jobs that are easy to understand. When it comes to resource allocation, they like to do it the natural way: assess resource requirements, define best practices, and allocate resources.</p>
<p>Despite its effectiveness, such a procedure is anti-automation. IaC forces system administrators to think in terms of scripts. Their responsibilities must be divided down or grouped into repeatable processes that may be scripted.</p>
<h4 id="heading-4-disposable-systems"><strong>4. Disposable Systems</strong></h4>
<p>To render hardware reliability insignificant to system operations, IaC relies heavily on reliable and robust software. Organizations must allow hardware failures to impact their businesses in the cloud era, since the underlying hardware may not always be trustworthy. As a result, software-level resource provisioning guarantees that in the event of a hardware breakdown, an alternate hardware allocation is quickly assigned to ensure that IT operations are not disrupted.</p>
<p>At the heart of IaC is fluid infrastructure that can be produced, destroyed, resized, transferred, and replaced. It should be able to seamlessly handle infrastructure changes such as resizing and expansions.</p>
<h4 id="heading-5-ever-evolving-design"><strong>5. Ever-evolving Design</strong></h4>
<p>The IT infrastructure design is always changing to meet the organization's changing needs. Because infrastructure modifications are costly, businesses aim to keep them to a minimum by rigorously anticipating future requirements and designing systems accordingly. Future adjustments will be considerably more difficult and costly as a result of these unnecessarily complex designs.</p>
<p>This challenge is addressed by IaC-driven cloud infrastructure, which simplifies change management. While present systems are designed to fulfil current needs, future modifications must be simple to adopt. The best way to ensure that change management is simple and quick is to make regular changes so that all stakeholders are aware of the usual concerns and can develop scripts to successfully address them.</p>
<h4 id="heading-6-self-documentation"><strong>6. Self-Documentation</strong></h4>
<p>The teams are constantly striving to ensure their paperwork stay relevant, useful, and accurate. Someone may develop a detailed paper for a new procedure, but it is uncommon for such documents to be maintained up to date as changes and adjustments are made to the way things are done. In addition, holes in records occur on a frequent basis. Several people come up with their own shortcuts and tweaks. Some people build their scripts to make the process go more smoothly.</p>
<p>Despite the fact that documentation is frequently employed to maintain continuity, conventions, and even legal enforcement, it is an exaggerated portrayal of what occurs in reality. The scripts, definition files, and resources that implement the policy with infrastructure as code encapsulate the stages for carrying out a process. Only a small amount of additional documentation is required to get people started. The current documentation should be kept near to the idea that it records so that it is readily available when individuals make adjustments.</p>
<hr />
<h3 id="heading-gitops-andamp-ioc">GitOps &amp; IoC</h3>
<p><strong><em>GitOps</em></strong> is an operational framework that integrates DevOps best practices for application development to infrastructure automation, such as version control, collaboration, compliance, and CI/CD tooling. While the software development lifecycle has become increasingly automated, infrastructure continues to be a primarily human operation requiring specialized teams.</p>
<p>With the increasing demands on today's infrastructure, infrastructure automation has become increasingly important. Modern infrastructure must be able to handle cloud resources effectively in order to support continuous deployments.</p>
<p>Another approach to implement IaC is to use GitOps, which extends IaC and provides a procedure (Pull Request Process) for applying changes to Production or any other environment. It could also feature a control loop that checks that the actual state of the infrastructure matches the desired state on a routine basis. It will, for example, ensure that any modifications made directly to infrastructure revert to the desired state as defined by source control.</p>
<h3 id="heading-a-real-life-example">A real-life Example</h3>
<p>A key restriction in software development is that the environment in which newly produced software code is tested must exactly match the actual environment in which such code will be deployed. The only method to ensure that new code does not conflict with current code definitions is to generate errors or conflicts that could endanger the entire system.</p>
<h4 id="heading-in-the-past-software-delivery-followed-a-pattern-like-this">In the past, software delivery followed a pattern like this</h4>
<p>A System Administrator would build up a physical server and install the operating system, including all necessary service packs and tuning, to match the status of the production environment's main running live machine.</p>
<p>The support database would then be handled by a Database Administrator, and the system would be handed over to a testing team.</p>
<p>The code/program would be delivered to the test machine by the developer, and the test team would execute many operational and compliance tests.</p>
<p>You can deploy the updated code to the live, operational environment once it has completed the full procedure. In many circumstances, the new code will not function properly, necessitating more troubleshooting and rework.</p>
<p>A live environment clone made with the same IaC as the live environment guarantees that if it works in the cloned environment, it will also work in the live environment.</p>
<p>Consider a software delivery pipeline that includes DEV, UAT, and Production environments. Given that those early environments are crucial for testing the quality and production readiness of a software build version, there appears to be no utility in having a DEV and UAT environment that isn't an exact mirror of the prod environment.</p>
<p>Virtualization made it possible to speed up this process, particularly when it came to constructing and maintaining a test server that would mimic the live environment. However, because the procedure was manual, a human would be required to develop and update the machine on a regular basis.</p>
<p>These processes got even more "<strong><em>AGILE</em></strong>" after the introduction of DevOps. Human intervention is replaced by automation in the server virtualization and testing phases, increasing productivity and efficiency.</p>
<h4 id="heading-it-is-now-attainable-for-the-developer-to-do-all-duties-by-himself">It is now attainable for the developer to do all duties by himself</h4>
<p>The developer creates the application code and configuration management-related instructions that will cause the virtualized environment, as well as other environments like the database, appliances, testing tools, delivery tools, and others, to take action.</p>
<p>The configuration management instructions will create a new virtual test environment with an application server and database instance that exactly mirrors the live operational environment structure, both in terms of service packs and versioning, as well as live data that is transferred to such virtual test environment, upon the delivery of new code. (This is the part of the process where Infrastructure as Code is used.)</p>
<p>Then, using a set of tools, the essential compliance checks, as well as error detection and resolution, will be carried out. After that, the updated code is ready to be deployed in a live IT environment.</p>
<h3 id="heading-technologies-andamp-tools">Technologies &amp; Tools</h3>
<p><a target="_blank" href="https://aws.amazon.com/cloudformation/"><em>AWS CloudFormation</em></a>, <a target="_blank" href="https://www.redhat.com/en/technologies/management/ansible"><em>Red Hat Ansible</em></a>, <a target="_blank" href="https://www.chef.io/"><em>Chef</em></a>, <a target="_blank" href="https://puppet.com/"><em>Puppet</em></a>, <a target="_blank" href="https://www.snowflake.com/"><em>SnowFlake</em></a>, and <a target="_blank" href="https://www.terraform.io/"><em>Terraform</em></a> are examples of infrastructure-as-code tools. Some tools employ a domain-specific language (DSL), while others use YAML or JSON as a standard template format.</p>
<p>When choosing a tool, companies should think about where they want to deploy it. AWS CloudFormation, for example, is designed to provision and manage infrastructure on AWS and integrates with other AWS services. Chef, on the other hand, works with on-premises servers as well as a variety of cloud provider infrastructure-as-a-service options.</p>
<hr />
<p>Hope you enjoyed reading this blog as much as I enjoyed writing it. If you have any comments or suggestions, please feel free to reach out ❤</p>
]]></content:encoded></item><item><title><![CDATA[How I Met Your Database -& Mainly Relational Using SQL-]]></title><description><![CDATA[This blog is gonna be Legen-WAIT FOR IT-dary! or at least I hope so. As you may have guessed I am a huge HIMYM fan.
In this blog we will give an introduction on SQL, the basic syntax, the joins and everything you need to start your way in handling Da...]]></description><link>https://amrtechuniverse.com/how-i-met-your-database-and-mainly-relational-using-sql</link><guid isPermaLink="true">https://amrtechuniverse.com/how-i-met-your-database-and-mainly-relational-using-sql</guid><category><![CDATA[SQL]]></category><category><![CDATA[Databases]]></category><category><![CDATA[Data Science]]></category><category><![CDATA[data analysis]]></category><category><![CDATA[Beginner Developers]]></category><dc:creator><![CDATA[Amr Khaled]]></dc:creator><pubDate>Tue, 01 Mar 2022 18:08:07 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/unsplash/2S0b9aTB7t0/upload/v1646065583493/G-u6H_Onm.jpeg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>This blog is gonna be Legen-WAIT FOR IT-dary! or at least I hope so. As you may have guessed I am a huge HIMYM fan.</p>
<p>In this blog we will give an introduction on SQL, the basic syntax, the joins and everything you need to start your way in handling Data from relational databases in general.</p>
<h2 id="heading-different-types-of-databases">Different types of Databases</h2>
<p>We deal with databases on an almost daily basis, even without computers. Every time we access our bank accounts, add a friend on any social media application or buy anything online really.</p>
<p>In 1970, <a target="_blank" href="https://www.britannica.com/biography/Edgar-Frank-Codd">Edgar F. Codd</a> of IBM published an academic paper titled, <a target="_blank" href="https://www.seas.upenn.edu/~zives/03f/cis550/codd.pdf">A Relational Model of Data for Large Shared Banks</a>. The paper introduced an innovative way to model data. It paved the way of building a group of cross-linked tables that would allow you to store data just once. Introducing the capability to find answers to any data that we need so long as the answer was stored somewhere in it. </p>
<p>In the 1980s and ’90s, relational databases skyrocketed; Making the ability to query and index data extremely efficient. Table joins and Transactions were introduced.</p>
<p>There are various types of databases, that include but are not limited to:</p>
<h4 id="heading-object-oriented-databases">Object-Oriented Databases</h4>
<p>The sort of database that stores data in the database system using an object-based data paradigm. The information is represented and saved as objects, which are analogous to the objects used in object-oriented programming.</p>
<p>Object databases are frequently employed in applications that call for high performance, calculations, and quick results. Real-time systems, architectural &amp; engineering for 3D modelling, telecommunications, and scientific products, molecular science, and astronomy are some of the common applications that use object databases.</p>
<h4 id="heading-network-databases">Network Databases</h4>
<p>The database is normally the one that follows the network data model. The data is represented in this manner as a network of nodes connected by links. It allows each record to have several children and parent nodes, forming a flexible network structure.</p>
<h4 id="heading-cloud-databases">Cloud Databases</h4>
<p>A database that stores information in a virtual environment and runs on a cloud computing platform. It offers users access to the database through a variety of cloud - based services. There are numerous cloud platforms available, however the below are the best:</p>
<ul>
<li>Amazon Web Services(AWS)</li>
<li>Microsoft Azure</li>
<li>Google Cloud SQL</li>
</ul>
<h4 id="heading-nosql-databases">NoSQL Databases</h4>
<p>Non-SQL databases are a form of database that can store a wide range of data sets. It is not a relational database because it stores data in a variety of formats, not only tabular. It was created in response to a rise in the need for modern applications. As a result, in response to the demands, NoSQL introduced a wide range of database systems. A NoSQL database can be further classified into the following four types:</p>
<ul>
<li><p>Key-value storage: It is the most basic sort of database storage, in which each object is stored as a key (or attribute name) that holds its value.</p>
</li>
<li><p>Document-oriented Database: A database that stores data in the form of a JSON-like document. It facilitates data storage for developers by using the same document-model format as the application code.</p>
</li>
<li><p>Graph Databases: It's a graph-like structure for storing large volumes of data. The graph database is most typically used by social networking websites.</p>
</li>
<li><p>Wide-column stores: It's akin to how data is stored in relational databases. Instead of storing data in rows, data is stored in huge columns.</p>
</li>
</ul>
<h4 id="heading-relational-databases">Relational Databases</h4>
<p>This database uses the relational data model, which stores data in the form of rows (tuples) and columns (attributes), which are combined to make a table (relation). SQL is used to store, manipulate, and maintain data in a relational database. Each table in the database has a key that distinguishes the data from that of other tables.</p>
<p>We will focus mainly in this blog on Relational databases and how to manage them using SQL.</p>
<hr />
<h2 id="heading-what-is-sql">What is SQL?</h2>
<p>SQL stands for <em>Structured Query Language</em>, It is the way by which you can manipulate the database and perform various operations like Inserting, updating or deleting records and creating tables.</p>
<p>SQL became an ANSI standard -American National Standards Institute-  in 1986, and of ISO -International Organization for Standardization- in 1987. However, there are different versions of the SQL language, they all support the major commands (such as <code>SELECT</code>, <code>UPDATE</code>, <code>DELETE</code>, <code>INSERT</code>, <code>WHERE</code>). You don't have to worry if all of that sounds gibberish to you right now as we will discuss each of these terms and more in details.</p>
<h2 id="heading-relational-databases-properties">Relational Databases Properties</h2>
<p>The <strong><em>ACID</em></strong> properties are the four most well-known properties of a relational model, and they are as follows:</p>
<ol>
<li><p>A means Atomicity: This assures that the data operation will complete successfully or unsuccessfully. It employs an all-or-nothing approach. A transaction, for example, will either be committed or aborted.</p>
</li>
<li><p>C means Consistency: If we conduct any operation on the data, its value should be retained both before and after the operation. For example, the account balance should be correct before and after the transaction, i.e., it should be conserved.</p>
</li>
<li><p>I means Isolation: There can be multiple concurrent users accessing data from the database at the same time. As a result, data isolation should be maintained. When many transactions occur at the same time, for example, one transaction's effects should not be apparent to the database's other transactions.</p>
</li>
<li><p>D means Durability: It ensures that data modifications are permanent after the process is completed and the data is committed.</p>
</li>
</ol>
<h4 id="heading-most-common-sql-commands">Most common SQL Commands</h4>
<p>You will work with these commands in an almost daily basis, as they are essential in working with any query:</p>
<ul>
<li><code>CREATE DATABASE</code>:  creates a new database</li>
<li><code>ALTER DATABASE</code>: modifies a database</li>
<li><code>CREATE TABLE</code>: creates a new table</li>
<li><code>ALTER TABLE</code>: modifies a table</li>
<li><code>DROP TABLE</code> : deletes a table</li>
<li><code>SELECT</code>: extracts data from a database</li>
<li><code>UPDATE</code>: updates data in a database</li>
<li><code>DELETE</code>: deletes data from a database</li>
<li><code>INSERT INTO</code>: inserts new data into a database</li>
</ul>
<p><strong>Note: SQL keywords are not case sensitive: <code>select</code> is the same as <code>SELECT</code> and can be used interchangeably. </strong> </p>
<h2 id="heading-sql-syntax">SQL Syntax</h2>
<p>One or more tables are commonly seen in a database. A name is assigned to each table (e.g. "Customers" or "Purchases"). Tables include data records (rows).</p>
<p>We'll utilize our HIMYM knowledge and create a really simple database in this blog.
The following is the script used to create the database, table and populating the table with some sample data:</p>
<pre><code>
IF NOT EXISTS(<span class="hljs-keyword">SELECT</span> * <span class="hljs-keyword">FROM</span> sys.databases <span class="hljs-keyword">WHERE</span> <span class="hljs-keyword">name</span> = <span class="hljs-string">'HIMYM'</span>)
  <span class="hljs-keyword">BEGIN</span>
    <span class="hljs-keyword">CREATE</span> <span class="hljs-keyword">DATABASE</span> HIMYM;
  <span class="hljs-keyword">END</span>;

<span class="hljs-keyword">use</span> HIMYM;

<span class="hljs-keyword">create</span> <span class="hljs-keyword">table</span> <span class="hljs-keyword">Characters</span>(
    <span class="hljs-keyword">id</span> <span class="hljs-built_in">INTEGER</span> PRIMARY <span class="hljs-keyword">KEY</span> <span class="hljs-keyword">IDENTITY</span> (<span class="hljs-number">1</span>, <span class="hljs-number">1</span>),
    CharacterName <span class="hljs-keyword">NVARCHAR</span>(<span class="hljs-number">32</span>) <span class="hljs-keyword">NOT</span> <span class="hljs-literal">NULL</span>,
    Age <span class="hljs-built_in">FLOAT</span>,
    Occupancy <span class="hljs-keyword">NVARCHAR</span>(<span class="hljs-number">32</span>)
);

<span class="hljs-keyword">INSERT</span> <span class="hljs-keyword">INTO</span> <span class="hljs-keyword">Characters</span>(CharacterName,Age,Occupancy)
<span class="hljs-keyword">VALUES</span>
(<span class="hljs-string">'Ted Mosby'</span>, <span class="hljs-number">27</span>, <span class="hljs-string">'Architect'</span>),
(<span class="hljs-string">'Marshall Eriksen'</span>, <span class="hljs-number">27</span>, <span class="hljs-string">'Law-Student'</span>),
(<span class="hljs-string">'Barney Stinson'</span>, <span class="hljs-number">29</span>, <span class="hljs-string">'PLEASE'</span>),
(<span class="hljs-string">'Lily Aldrin'</span>, <span class="hljs-number">27</span>, <span class="hljs-string">'Pre-School Teacher'</span>),
(<span class="hljs-string">'Robin Scherbatsky'</span>, <span class="hljs-number">25</span>, <span class="hljs-string">'News Reporter'</span>);
</code></pre><p>We performed a lot of operations in the script above , so let's provide a brief step-by-step explanation:</p>
<ol>
<li>Checking if the database exists and if it does not, then we create it.</li>
<li>We then utilize the <code>USE</code> keyword to specify the database that we will use in the rest of the script to avoid any ambiguity.</li>
<li>Creating our Characters table with the specified columns (id, Character Name, Age &amp; Occupation)</li>
<li>Populating the Characters table with some sample data.</li>
</ol>
<p>We will dive deeper into <code>PRIMARY KEYS</code>, <code>FOREIGN KEYS</code>, <code>IDENTITY</code> &amp; more SQL features and keywords in further blogs; so you do not have to worry about them right now if you do not understand them.</p>
<hr />
<p>if we run the query <code>SELECT * FROM Characters</code>, we will retrieve the following data:</p>
<pre><code><span class="hljs-string">id</span>    <span class="hljs-string">CharacterName</span>         <span class="hljs-string">Age</span>         <span class="hljs-string">Occupancy</span>
<span class="hljs-number">1</span>    <span class="hljs-string">Ted</span> <span class="hljs-string">Mosby</span>              <span class="hljs-number">27</span>          <span class="hljs-string">Architect</span>
<span class="hljs-number">2</span>    <span class="hljs-string">Marshall</span> <span class="hljs-string">Eriksen</span>       <span class="hljs-number">27</span>         <span class="hljs-string">Law-Student</span>
<span class="hljs-number">3</span>    <span class="hljs-string">Barney</span> <span class="hljs-string">Stinson</span>         <span class="hljs-number">29</span>           <span class="hljs-string">PLEASE</span>
<span class="hljs-number">4</span>    <span class="hljs-string">Lily</span> <span class="hljs-string">Aldrin</span>            <span class="hljs-number">27</span>      <span class="hljs-string">Pre-School</span> <span class="hljs-string">Teacher</span>
<span class="hljs-number">5</span>    <span class="hljs-string">Robin</span> <span class="hljs-string">Scherbatsky</span>      <span class="hljs-number">25</span>        <span class="hljs-string">News</span> <span class="hljs-string">Reporter</span>
</code></pre><p>We have five records, each row corresponds to a unique character with each column holding all information linked with a certain field.</p>
<p>Let's breakdown this simple select query structure and understand what each keyword does; the general structure of a query contains the table name, selected columns to retrieve and the condition to retrieve by.</p>
<pre><code><span class="hljs-keyword">SELECT</span> <span class="hljs-built_in">column_name</span>(s)
<span class="hljs-keyword">FROM</span> <span class="hljs-built_in">table_name</span>
<span class="hljs-keyword">WHERE</span> condition;
</code></pre><p>In our example we did not have a <code>WHERE</code> condition but we will dig deeper on when to use it later on.</p>
<ul>
<li><code>SELECT</code>: used to retrieve data.</li>
<li><code>*</code>: a wildcard expression used to indicate that we want to retrieve all the columns in our query.</li>
<li><code>From table_name</code>: the name of the table from which we want to retrieve our data.</li>
</ul>
<hr />
<p>Phew! that was a lot of information if you are still new to the world of databases &amp; SQL, that's it for this blog and In the upcoming blog posts, we will start going deeper into SQL and provide an introduction to programming with python as part of our coding &amp; data analysis journey!</p>
<p>Hope you enjoyed reading this blog as much as I enjoyed writing it. If you have any comments or suggestions please feel free to reach out ❤</p>
]]></content:encoded></item><item><title><![CDATA[Intro To Data Analysis]]></title><description><![CDATA[Hello and welcome to the second blog in a series of blogs where we discuss topics like Data Analysis, AI, Machine Learning and much much more.
This is the continuation in which we start by talking about Data Analysis. Don't worry we are still keeping...]]></description><link>https://amrtechuniverse.com/intro-to-data-analysis</link><guid isPermaLink="true">https://amrtechuniverse.com/intro-to-data-analysis</guid><category><![CDATA[Data Science]]></category><category><![CDATA[data analysis]]></category><category><![CDATA[Beginner Developers]]></category><category><![CDATA[Python]]></category><category><![CDATA[R Language]]></category><dc:creator><![CDATA[Amr Khaled]]></dc:creator><pubDate>Sat, 26 Feb 2022 21:30:18 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/unsplash/qwtCeJ5cLYs/upload/v1645874675225/19_gHaRIG.jpeg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>Hello and welcome to the second blog in a series of blogs where we discuss topics like Data Analysis, AI, Machine Learning and much much more.</p>
<p>This is the continuation in which we start by talking about Data Analysis. Don't worry we are still keeping things simple and will not introduce coding examples just yet.</p>
<h2 id="heading-what-is-data-analysis">What is Data Analysis?</h2>
<p>As we have discussed in our previous <a target="_blank" href="https://amrkh97.hashnode.dev/data-analysis-ai-machine-learning-and-everything-in-between-part-1">blog</a>, Data analysis is the process of cleaning, transforming, and modeling data to discover useful information that will help us make informed business decisions.</p>
<h2 id="heading-why-is-data-analysis-gaining-traction">Why is Data Analysis gaining traction?</h2>
<p>Data Analysis is not a new concept it has been around since the 1940's. One of the most famous examples is Henry Ford started measuring the speed of assembly lines, Analytics started becoming more mainstream when computers became a crucial part of the decision making process and providing more insights, with the development of Big data &amp; the cloud; Data Analysis has started evolving dramatically. It involved gathering data from various sources, searching for patterns &amp; creating data insights that help making much more informed decisions.</p>
<h2 id="heading-data-analysis-andamp-statistics">Data Analysis &amp; Statistics</h2>
<p>Data Analaysis is deeply intertwined with a wide variety of statistical methods; you don't have to worry if you have no background in statistics, but going forward if you want to pursue a further career; you will need to familiarize yourself with it to better know how to handle various types of data. Almost all libraries and tools already support built-in methods to handle different types of data.</p>
<p>Statistics deals with:</p>
<ul>
<li>Data Acquisition </li>
<li>Data Interpretation </li>
<li>Data Validation </li>
</ul>
<p>An example for how statistics helps is if we have a supermarket. Let's assume that we want to identify what are our clients most frequently purchase, we can analyze the invoices and group the items by their frequency and Voila! we know now the best and worst performing items.</p>
<h2 id="heading-role-of-data-analytics">Role Of Data Analytics</h2>
<p>Let's apply the supermarket example to what we are trying to explain in this section.</p>
<ol>
<li><p>Gathering Hidden Insights:
Analyzing customer's putchasing patterns.</p>
</li>
<li><p>Generating Reports:
Getting the reports for how various items are performing to make better decisions by the management/decision makers for restocking or changing brands.</p>
</li>
<li><p>Market Analysis:
Understanding the points of strength and weaknesses against our competitors and what is our store's edge.</p>
</li>
</ol>
<h2 id="heading-data-analysis-process">Data Analysis Process</h2>
<p>The Data Analysis process consists of <strong>Five</strong> Iterational steps:</p>
<ul>
<li><p><strong>Identify</strong> What is the business requirement that we are trying to solve or what is the obstacle currently facing us?</p>
</li>
<li><p><strong>Collect</strong> the raw data that we will need to help answer the identified question. It can come from various sources as mentioned before and It can be like the sales invoices to our customers in the supermarket example. </p>
</li>
<li><p><strong>Clean</strong> the data. This often involves removing duplicates, inconsistencies &amp; standardizing the format, and dealing with white spaces and other syntax errors.</p>
</li>
<li><p><strong>Analyze</strong> the data. By manipulating the data using various data analysis techniques and tools - That we will discuss in details later on -, you can begin to find trends &amp; correlations that begin to tell a story about how our business is doing or how are our customers reacting to various changes.</p>
</li>
<li><p><strong>Interpret</strong> the results of your analysis to see how well you answered your original question and what recommendations can you make based on the data.</p>
</li>
</ul>
<h2 id="heading-tools-used-in-data-analysis">Tools used in Data Analysis</h2>
<ul>
<li><p><a target="_blank" href="https://www.r-project.org/other-docs.html">R Programming</a>:
The leading tool for analytics, statistics &amp; data modelling; It pre-installs all packages and runs on Unix, Windows &amp; Mac OS.</p>
</li>
<li><p><a target="_blank" href="https://www.python.org/doc/">Python</a>:
Python is an open-source language that is easy to learn. We will discuss it in further blogs so if you have no background don't worry.
Python has numerous packages that can aid you in your Data Analytics journey like: Sci-Kit Learn, Numpy &amp; Pandas.</p>
</li>
<li><p>Excel:
One of the most famous Microsoft applications, It is mostly used for Internal sheets data &amp; Comma separated files (CSV).</p>
</li>
</ul>
<p>There are a plethora of tools when it comes to data analysis, some more advanced like: </p>
<ul>
<li>Apache Spark</li>
<li>Tableau</li>
<li>SAS</li>
</ul>
<p>But for someone still getting to know the world of data analysis, you have come a long way and learned some of the basics that pave your way to start your own journey.</p>
<hr />
<p>In the upcoming blog posts, we will dig deeper into SQL, Python &amp; R and Implementing a small project to get our coding &amp; data analysis journey started!</p>
<p>Hope you enjoyed reading this blog as much as I enjoyed writing it. If you have any comments or suggestions please feel free to reach out ❤</p>
]]></content:encoded></item></channel></rss>