Spring Boot Backend Development Course, Database, What is a Database

Welcome to the Spring Boot Backend Development Course. One of the topics of this course is ‘Databases’. When developing web applications, databases are essential, and all data must be stored and managed. In this post, we will start with the basic concepts of databases, and then explore various types, database design, integration with Spring Boot, and how to use SQL in detail.

1. Definition of a Database

A database is a system that helps to store and manage information structurally. Users can perform various tasks such as entering, modifying, deleting, and querying data. Databases are generally needed for efficient storage, retrieval, management, and protection of data. Through databases, multiple users can access data simultaneously, ensuring data integrity.

1.1 Necessity of Databases

Databases are necessary for many reasons. These include:

  • Structured Data Management: Databases provide a structure for organizing and efficiently managing data.
  • Data Integrity: Databases ensure the consistency and accuracy of data.
  • Concurrency Management: They allow multiple users to access and modify data simultaneously.
  • Data Security: Databases protect data by setting access controls and user permissions.

2. Types of Databases

Databases can primarily be classified as follows:

2.1 Relational Databases (RDBMS)

Relational databases store data in tabular form. Each table consists of rows and columns, and their relationships are defined by foreign keys. Notable relational database management systems (RDBMS) include MySQL, PostgreSQL, and Oracle.

2.2 Non-relational Databases (NoSQL)

Non-relational databases are suitable for storing and managing unstructured data. They can store data in formats such as JSON, XML, documents, and key-value pairs, with a flexible schema. Representative non-relational databases include MongoDB, Cassandra, and Redis.

2.3 Graph Databases

Graph databases are optimized for modeling relationships between data. They use nodes and edges to store data and can visually represent complex relationships. Neo4j is a representative example of a graph database.

3. Database Design

Database design is essential for building an efficient database. The database design process includes requirement analysis, conceptual design, logical design, and physical design.

3.1 Requirement Analysis

The first stage of database design is requirement analysis. Here, we identify the information needed by the users and the business requirements.

3.2 Conceptual Design

In the conceptual design stage, the conceptual structure of the data is defined through an ER diagram. This involves identifying ‘entities’, ‘attributes’, and ‘relationships’.

3.3 Logical Design

In the logical design stage, the conceptual design is transformed into a data model (typically a relational model). At this stage, the schema of the database is determined.

3.4 Physical Design

Finally, in the physical design stage, the logical design is specified according to the actual database system. This process involves optimizations considering performance, including indexing and partitioning.

4. Integration of Spring Boot and Databases

Spring Boot provides various features that make it easy to integrate with databases. The process of connecting to a database using Spring Boot includes dependency management, database configuration, defining entity classes, and creating repository interfaces.

4.1 Dependency Management

To communicate with a database in Spring Boot, appropriate dependencies must be added. If you are using Maven, the following dependencies should be added to the `pom.xml` file:



    org.springframework.boot
    spring-boot-starter-data-jpa


    com.h2database
    h2
    runtime


4.2 Database Configuration

To configure the database in Spring Boot, the `application.properties` file must be modified. Here is an example of H2 database configuration:


spring.datasource.url=jdbc:h2:mem:testdb
spring.datasource.driver-class-name=org.h2.Driver
spring.datasource.username=sa
spring.datasource.password=
spring.h2.console.enabled=true
spring.jpa.hibernate.ddl-auto=update

4.3 Defining Entity Classes

Entity classes must be defined in Spring Boot that map to database tables. For example, a `User` entity that stores user information could be defined as follows:


import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;

@Entity
public class User {

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long id;
    private String name;
    private String email;

    // getters and setters
}

4.4 Creating Repository Interfaces

Through the Repository interface, you can interact with the database. The `UserRepository` is defined as follows:


import org.springframework.data.jpa.repository.JpaRepository;

public interface UserRepository extends JpaRepository {
}

5. How to Use SQL

SQL (Structured Query Language) is the standard language used to interact with databases. With SQL, you can query, insert, modify, and delete data. The basic SQL syntax is as follows:

5.1 Data Query: SELECT


SELECT * FROM users; 

5.2 Data Insertion: INSERT


INSERT INTO users (name, email) VALUES ('John Doe', 'john.doe@example.com'); 

5.3 Data Modification: UPDATE


UPDATE users SET email = 'john.new@example.com' WHERE id = 1; 

5.4 Data Deletion: DELETE


DELETE FROM users WHERE id = 1; 

Conclusion

In this post, we explored the basic concepts of databases, their types, design methods, and integration with Spring Boot. Since databases play a crucial role in backend development, it is important to have a fundamental understanding and practical use of them. In future courses, we plan to cover a variety of topics related to databases, so please look forward to it.

Spring Boot Backend Development Course, Database, Understanding Project with Diagrams

Hello! Today we will conduct a backend development course using Spring Boot. In this course, we will take a detailed look at the basics of Spring Boot, database integration, REST API development, and finally how to understand the project structure through diagrams.

1. What is Spring Boot?

Spring Boot is a framework that helps you use the Java-based Spring framework more easily. It supports developers in building applications quickly and allows you to create executable Spring applications without complex configurations.

The main features of Spring Boot are as follows:

  • Auto configuration: Automatically configures Spring settings.
  • Standalone applications: Can be easily packaged into a JAR file for deployment and execution.
  • Production-ready: Provides external configuration features and monitoring metrics.
  • Starter dependencies: Helps to easily add necessary dependencies.

2. Setting Up the Development Environment

To use Spring Boot, you need to install the Java Development Kit (JDK) and choose an IDE (Integrated Development Environment). In this course, we will use IntelliJ IDEA.

2.1 Installing the JDK

The JDK can be downloaded from the official Oracle website or OpenJDK. After installation, you need to set the PATH environment variable to use the JDK.

2.2 Installing IntelliJ IDEA

IntelliJ IDEA is an IDE provided by JetBrains. The Community Edition is offered for free and is suitable for Spring Boot development. Download and install it from the official website.

3. Creating a Spring Boot Project

Now let’s create a new Spring Boot project. Click on “New Project” in IntelliJ IDEA and select “Spring Initializr”.

3.1 Project Settings

Enter the following information:

  • Group: com.example
  • Artifact: demo
  • Name: demo
  • Description: Demo project for Spring Boot
  • Package name: com.example.demo
  • Packaging: Jar
  • Java: 11

Then, in “Dependencies”, add “Spring Web”, “Spring Data JPA”, and “H2 Database”.

4. Integrating with the Database

Spring Boot supports easy integration with various databases. In this course, we will create a simple CRUD application using the H2 database.

4.1 H2 Database Configuration

The H2 database is an in-memory database. Configure it by adding the following to the project’s src/main/resources/application.properties file:

spring.datasource.url=jdbc:h2:mem:testdb
spring.datasource.driverClassName=org.h2.Driver
spring.datasource.username=sa
spring.datasource.password=
spring.h2.console.enabled=true

4.2 Creating the Entity Class

Now let’s create the Entity class that will be mapped to the database. Create a “model” package, and write the User class as follows:

package com.example.demo.model;

import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;

@Entity
public class User {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;
    private String name;
    private String email;

    // Getters and Setters
}

4.3 Creating the Repository Interface

To interact with the database using Spring Data JPA, create a Repository interface. Create a ‘repository’ package and write the interface as follows:

package com.example.demo.repository;

import com.example.demo.model.User;
import org.springframework.data.jpa.repository.JpaRepository;

public interface UserRepository extends JpaRepository {
}

4.4 Creating the Service Class

Create a Service class to handle business logic. Create a ‘service’ package and write the UserService class as follows:

package com.example.demo.service;

import com.example.demo.model.User;
import com.example.demo.repository.UserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class UserService {

    @Autowired
    private UserRepository userRepository;

    public List findAll() {
        return userRepository.findAll();
    }

    public User save(User user) {
        return userRepository.save(user);
    }
}

4.5 Creating the Controller Class

Create a Controller class to handle HTTP requests. Create a ‘controller’ package and write the UserController class as follows:

package com.example.demo.controller;

import com.example.demo.model.User;
import com.example.demo.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/users")
public class UserController {

    @Autowired
    private UserService userService;

    @GetMapping
    public List getAllUsers() {
        return userService.findAll();
    }

    @PostMapping
    public User createUser(@RequestBody User user) {
        return userService.save(user);
    }
}

5. Understanding RESTful APIs

Now let’s understand RESTful APIs using Spring Boot. REST stands for Representational State Transfer and is a web-based architectural style. RESTful APIs operate by creating, reading, modifying, and deleting resources through HTTP requests.

5.1 HTTP Methods

RESTful APIs use the following HTTP methods:

  • GET: Retrieve resources
  • POST: Create resources
  • PUT: Modify resources
  • DELETE: Delete resources

5.2 JSON Data

JSON (JavaScript Object Notation) format is commonly used to transmit data in RESTful APIs. JSON is a lightweight and human-readable data format widely used in web applications.

6. Understanding Project Structure Through Diagrams

Based on what we have discussed so far, let’s draw the project structure. Here is the overall project structure:

demo
├── src
│   ├── main
│   │   ├── java
│   │   │   └── com.example.demo
│   │   │       ├── controller
│   │   │       │   └── UserController.java
│   │   │       ├── model
│   │   │       │   └── User.java
│   │   │       ├── repository
│   │   │       │   └── UserRepository.java
│   │   │       └── service
│   │   │           └── UserService.java
│   │   └── resources
│   │       └── application.properties
└── pom.xml

7. Conclusion

In this course, we learned the basics of backend development using Spring Boot and how to implement a simple RESTful API integrated with a database. Spring Boot is a powerful framework, so I encourage you to continue learning and take advantage of its various features.

Don’t stop here; take on various projects! We wish you success on your development journey!

Course on Spring Boot Backend Development, Writing GitHub Action Scripts, CI

This course focuses on how to develop backend applications using Spring Boot and how to write GitHub Actions scripts to build a continuous integration (CI) pipeline. By the end of this article, you will acquire the necessary skills to build web applications with Spring Boot and set up a CI/CD process.

1. What is Spring Boot?

Spring Boot is a framework that helps you develop applications based on the Spring framework quickly and easily. It provides auto-configuration, embedded servers, and easy deployment features, allowing developers to add necessary functionalities conveniently.

  • Auto-configuration: Spring Boot automatically configures the application’s settings, enabling developers to start projects with minimal configuration.
  • Embedded servers: It includes servers like Tomcat, Jetty, and Undertow, allowing applications to run without separate server setup.
  • Modularity: Spring Boot is designed to offer various starter packs, making it easy to add necessary libraries.

2. Setting Up the Spring Boot Development Environment

Let’s take a look at the environmental setup steps necessary to start with Spring Boot. This includes installing the JDK, setting up the IDE, and creating your Spring Boot project.

2.1 Install JDK

You need the Java Development Kit (JDK) to develop with Spring Boot. Install JDK version 11 or higher. You can download the JDK from the [Oracle official website](https://www.oracle.com/java/technologies/javase-jdk11-downloads.html) or [OpenJDK](https://jdk.java.net/).

2.2 Install IDE

The most commonly used IDEs for Spring Boot development are IntelliJ IDEA and Eclipse. The Community Edition of IntelliJ IDEA is available for free and offers powerful features. Download and install [IntelliJ IDEA](https://www.jetbrains.com/idea/download/).

2.3 Create a Spring Boot Project

You can create a Spring Boot project using [Spring Initializr](https://start.spring.io/). Follow the steps below to create your project:

  1. Visit the site and input as follows:
    • Project: Maven Project
    • Language: Java
    • Spring Boot: Select the latest stable version
    • Group: com.example
    • Artifact: demo
    • Dependencies: Add Spring Web, Spring Data JPA, H2 Database
  2. Click the “Generate” button to download the project.
  3. Open the downloaded project in your IDE and run the build.

3. Creating a Simple REST API

Now, let’s create a simple REST API. We will implement basic CRUD (Create, Read, Update, Delete) functionalities.

3.1 Writing the Entity Class

First, we write the entity class that will be mapped to the database table. The class to be used is as follows:

package com.example.demo.model;

import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;

@Entity
public class Item {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;
    private String name;
    private double price;

    // Getters and setters
    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public double getPrice() {
        return price;
    }

    public void setPrice(double price) {
        this.price = price;
    }
}

3.2 Writing the Repository

Next, we write a JPA repository to interact with the database:

package com.example.demo.repository;

import com.example.demo.model.Item;
import org.springframework.data.jpa.repository.JpaRepository;

public interface ItemRepository extends JpaRepository<Item, Long> {
}

3.3 Writing the Service Class

We will now add a service class to handle the business logic:

package com.example.demo.service;

import com.example.demo.model.Item;
import com.example.demo.repository.ItemRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class ItemService {
    @Autowired
    private ItemRepository itemRepository;

    public List findAll() {
        return itemRepository.findAll();
    }

    public Item save(Item item) {
        return itemRepository.save(item);
    }

    public Item update(Long id, Item item) {
        item.setId(id);
        return itemRepository.save(item);
    }

    public void delete(Long id) {
        itemRepository.deleteById(id);
    }
}

3.4 Writing the Controller

Finally, we create a controller to provide REST API endpoints:

package com.example.demo.controller;

import com.example.demo.model.Item;
import com.example.demo.service.ItemService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/api/items")
public class ItemController {
    @Autowired
    private ItemService itemService;

    @GetMapping
    public List<Item> getAllItems() {
        return itemService.findAll();
    }

    @PostMapping
    public Item createItem(@RequestBody Item item) {
        return itemService.save(item);
    }

    @PutMapping("/{id}")
    public Item updateItem(@PathVariable Long id, @RequestBody Item item) {
        return itemService.update(id, item);
    }

    @DeleteMapping("/{id}")
    public void deleteItem(@PathVariable Long id) {
        itemService.delete(id);
    }
}

4. Introduction to GitHub Actions

GitHub Actions is a tool that automates CI/CD (Continuous Integration and Continuous Delivery) tasks in software development. It allows developers to set up automated execution of build, test, and deployment processes.

4.1 Reasons to Use GitHub Actions

  • Automated CI/CD Setup: Build and deployment can occur automatically with every code change.
  • Enhanced Collaboration: Multiple team members can work simultaneously with minimal conflicts.
  • No Location Constraints: Operates on cloud infrastructure, so no server setup is required.

5. Setting Up GitHub Actions

Now, let’s create a GitHub Actions workflow file for the Spring Boot application.

5.1 Creating a GitHub Repository

First, create a new repository on GitHub and commit your Spring Boot project there.

5.2 Creating the Workflow File

Create a folder named “.github/workflows” in the project root directory and create a file named “ci.yml” inside that folder.

name: CI

on:
  push:
    branches:
      - main

jobs:
  build:
    runs-on: ubuntu-latest

    steps:
      - name: Check out code
        uses: actions/checkout@v2

      - name: Set up JDK 11
        uses: actions/setup-java@v2
        with:
          java-version: '11'

      - name: Build with Maven
        run: mvn clean install

      - name: Run tests
        run: mvn test

The above code runs GitHub Actions every time code is pushed to the `main` branch. Each step performs the following tasks:

  • Checks out the code.
  • Sets up JDK 11.
  • Builds the project using Maven.
  • Runs tests.

5.3 Confirming GitHub Actions Execution

After pushing the code, you can check the ‘Actions’ tab in GitHub to see if the workflow runs successfully. If any issues occur, you can check the logs to identify and fix errors.

6. Continuous Deployment (CD)

In this section, we will look at additional configuration for deployment automation. This includes using AWS, Heroku, or other cloud hosting services for deployment.

6.1 Deploying to AWS EC2

You can deploy your application by creating an AWS EC2 instance. Here’s a simple setup method:

  1. Log in to AWS and create an instance from the EC2 dashboard.
  2. Set up a security group to allow port 8080.
  3. SSH into the instance to install JDK and Maven.
  4. Copy and run the application:
  5. java -jar yourapp.jar
    

6.2 Deploying to Heroku

Heroku is a platform that allows for easy and quick deployment of applications. You can deploy your application using the Heroku CLI:

  1. Install the Heroku CLI and log in.
  2. Create an application with the following command:
  3. heroku create your-app-name
    
  4. Push your code to deploy:
  5. git push heroku main
    

7. Conclusion

This course covered backend development using Spring Boot and how to automate CI/CD setup with GitHub Actions. By combining the powerful features of Spring Boot with GitHub Actions, you can enhance your development efficiency. Through continuous learning and practice, I hope you can grow into a more advanced application developer.

8. References

Spring Boot Backend Development Course, Writing GitHub Action Scripts, CD

Writing GitHub Action Scripts: Continuous Deployment (CD)

In modern software development, Continuous Deployment (CD) and Continuous Integration (CI) are essential elements. Automating these processes can significantly enhance developer productivity, especially when developing backend applications using Spring Boot. In this tutorial, we will explore how to automatically deploy a Spring Boot application using GitHub Actions.

1. What is Spring Boot?

Spring Boot is an open-source framework that extends the Spring Framework, making it easier to develop standalone Spring applications. It provides several useful features that simplify and expedite the use of the existing Spring Framework. Notably, it reduces the burden of initial setup and supports rapid application execution through built-in servers (e.g., Tomcat, Jetty).

2. What is GitHub Actions?

GitHub Actions is a CI/CD tool provided by GitHub that detects changes in the code and allows tasks to be executed automatically. Users can define and manage workflows in YAML file format, which can be triggered by various events (push, issue creation, etc.). This allows for the automation of tasks such as testing, building, and deployment.

3. Prerequisites

  • You should have already developed or created a Spring Boot application.
  • You need to create a GitHub repository for the project.
  • A GitHub account is required to use GitHub Actions.

4. Creating a Spring Boot Application

To create a Spring Boot application, you can use Spring Initializr. Set the appropriate meta information and add necessary dependencies to download the project. For example, you can select web (application), JPA, and H2 database.

 
// Example Maven dependency (pom.xml)
<dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-data-jpa</artifactId>
    </dependency>
    <dependency>
        <groupId>com.h2database</groupId>
        <artifactId>h2</artifactId>
        <scope>runtime</scope>
    </dependency>
</dependencies>

5. Creating a GitHub Repository

Access GitHub and create a new repository. Set the repository name according to the project, and you may select the ‘Initialize this repository with a README’ option. Then, push your local project to the GitHub repository.


# Run in the local project directory
git init
git add .
git commit -m "Initial commit"
git branch -M main
git remote add origin https://github.com/username/repository.git
git push -u origin main

6. Writing a GitHub Actions Workflow

Now you need to create a GitHub Actions workflow file. Create a YAML file under the `.github/workflows` directory. For example, create a file named `ci.yml` and write the following:


name: CI

on:
  push:
    branches:
      - main

jobs:
  build:
    runs-on: ubuntu-latest

    steps:
      - name: Check out code
        uses: actions/checkout@v2

      - name: Set up JDK 11
        uses: actions/setup-java@v2
        with:
          java-version: '11'
          distribution: 'adopt'

      - name: Build with Maven
        run: mvn clean package

7. Writing the Deployment Workflow

After setting up the basic CI workflow, it is time to write the workflow for CD. Here, we will describe the process of deploying to AWS EC2 as an example. Create a new YAML file named `deploy.yml` and write the following:


name: Deploy to EC2

on:
  push:
    branches:
      - main

jobs:
  deploy:
    runs-on: ubuntu-latest

    steps:
      - name: Check out code
        uses: actions/checkout@v2

      - name: Set up JDK 11
        uses: actions/setup-java@v2
        with:
          java-version: '11'
          distribution: 'adopt'

      - name: Build with Maven
        run: mvn clean package

      - name: Deploy to EC2
        uses: appleboy/scp-action@master
        with:
          host: ${{ secrets.EC2_HOST }}
          username: ${{ secrets.EC2_USER }}
          key: ${{ secrets.EC2_SSH_KEY }}
          port: 22
          source: target/*.jar
          target: /path/to/deploy/

The `appleboy/scp-action` used here helps send files to the EC2 instance using SSH. Each item can be stored in GitHub Secrets to enhance security.

8. Setting Up GitHub Secrets

You now need to set up secret variables used in the CI/CD workflow. Go to the ‘Settings’ -> ‘Secrets and variables’ -> ‘Actions’ of the GitHub repository page and add the secret variables to be hidden. For example:

  • EC2_HOST: IP address of the EC2 instance
  • EC2_USER: SSH username
  • EC2_SSH_KEY: SSH private key

9. Checking GitHub Actions Execution

Once all configurations are complete, commit and push to the main branch of the repository. This will automatically trigger GitHub Actions, executing the configured CI/CD process. You can check the execution logs in the ‘Actions’ tab to verify the success of each step.

10. Conclusion

In this tutorial, we learned how to automatically deploy a Spring Boot backend application using GitHub Actions. GitHub Actions allows you to set up CI/CD processes with just a simple YAML file, making it a powerful tool for automating various tasks. This can enhance developer productivity and improve the reliability of deployments. Additionally, you might consider extensions such as integrating with other cloud providers or deploying with Docker.

References

Spring Boot Backend Development Course, Create a GitHub Repository and Push Code

Spring Boot is a framework that helps to easily develop web applications based on Java. In this tutorial, we will explain in detail how to build a simple backend application using Spring Boot and save it on GitHub. After developing the application, we will guide you through the process of creating a GitHub repository and pushing the code.

Table of Contents

  • 1. Introduction to Spring Boot
  • 2. Setting Up Development Environment
  • 3. Creating a Simple Spring Boot Application
  • 4. Creating a GitHub Repository
  • 5. Pushing Code
  • 6. Conclusion and Additional Resources

1. Introduction to Spring Boot

Spring Boot is a tool provided to build applications quickly and reliably based on the Spring Framework. Spring Boot simplifies configuration and helps developers run applications with minimal effort through auto-configuration.

The main features of Spring Boot are as follows:

  • Auto-configuration: Spring Boot automatically handles the basic configuration needed for the project.
  • Starter dependencies: Starter dependencies are provided to easily add various features.
  • Embedded web server: Servers like Tomcat and Jetty are embedded, allowing applications to run without separate installation.
  • Monitoring and management in production: Spring Boot offers various features to monitor and manage applications in production.

2. Setting Up Development Environment

Required Tools Installation

To configure a stable development environment, the following tools are required:

  • Java Development Kit (JDK): JDK is necessary to run Spring Boot. You need to install JDK version 8 or higher.
  • IntelliJ IDEA or Eclipse: These are IDEs for developing Spring Boot applications. IntelliJ IDEA is available in both free and paid versions, while Eclipse is a free IDE that can be used on all platforms.
  • Git: A tool for version control. You can use Git to track code changes and push changes to a remote repository.
  • GitHub account: A GitHub account is needed to create a GitHub repository for code storage. You can sign up here.

Installation Procedure for Development Environment

The methods for installing each tool are as follows:

1. Install JDK

The JDK can be downloaded from the Oracle website. Choose the version suitable for your operating system and install it.

2. Install IDE

IntelliJ IDEA can be downloaded from JetBrains’ official website, and Eclipse can be downloaded from the Eclipse website. After installing the IDE, set the JDK path in the IDE.

3. Install Git

Git can be downloaded and installed from the official website. After installation, run the command git --version in the Command Line or Terminal to verify that the installation is complete.

3. Creating a Simple Spring Boot Application

Now, let’s actually create a Spring Boot application. You can create the application through the following steps.

Step 1: Initialize Spring

To initialize a Spring Boot project, use Spring Initializr.

  • Project: Choose (‘Maven Project’ or ‘Gradle Project’)
  • Language: Select ‘Java’.
  • Spring Boot: Choose the latest Spring Boot version.
  • Group: Enter, for example, com.example.
  • Artifact: Enter the desired project name. For example, set it as my-spring-boot-app.
  • Dependencies: Select Spring Web. You can add other dependencies as needed.

After finishing the setup, click the Generate button to download the project as a ZIP file.

Step 2: Import Project in IDE

Import the downloaded ZIP file into the IDE. To do this, open the IDE and select File -> Open to open the ZIP file, or you can extract the ZIP file and open the folder.

Step 3: Write Basic Code

Once the project structure is set up, open the src/main/java/com/example/myspringbootapp/MySpringBootApp.java file and update it with the following code:

package com.example.myspringbootapp;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class MySpringBootApp {

    public static void main(String[] args) {
        SpringApplication.run(MySpringBootApp.class, args);
    }
}

This is the starting point of a simple Spring Boot application. Now let’s create a simple REST API.

Step 4: Write REST Controller

First, create a new class file GreetingController.java. Write it as follows:

package com.example.myspringbootapp;

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class GreetingController {
    
    @GetMapping("/greeting")
    public String greeting(@RequestParam(value = "name", defaultValue = "World") String name) {
        return String.format("Hello, %s!", name);
    }
}

The above code creates a /greeting API endpoint that receives a name as a query parameter and returns a greeting message.

Step 5: Run the Application

You can run the main class (MySpringBootApp) in the IDE or execute the following command in the terminal to start the application:

./mvnw spring-boot:run

You can call the API by entering http://localhost:8080/greeting in the browser. If you enter http://localhost:8080/greeting?name=Alice, you will receive the message “Hello, Alice!”.

4. Creating a GitHub Repository

Now it’s time to save the Spring Boot application on GitHub. To upload the code we have created, we first need to create a GitHub repository.

Step 1: Log in to GitHub

First, log in to GitHub. If you don’t have an account, you need to sign up.

Step 2: Create a New Repository

After logging in, click the “+” button at the top right and select “New repository”. Enter the repository name and description, choose either Public or Private, and then click the Create repository button.

5. Pushing Code

Now let’s go through the process of pushing the code you have written locally to the GitHub repository.

Step 1: Initialize Git

Navigate to the project folder and initialize Git. Run the following command in the terminal:

git init

Step 2: Add GitHub Remote Repository

Next, add the address of the repository you created on GitHub. You can copy the repository’s URL from the top URL bar on GitHub:

git remote add origin https://github.com/USERNAME/REPOSITORY_NAME.git

Here, USERNAME is your GitHub username, and REPOSITORY_NAME is the repository name you created.

Step 3: Add and Commit Changes

To commit changes, run the following commands:

git add .
git commit -m "Initial commit"

Step 4: Push Code

Finally, push the local changes to GitHub:

git push -u origin master

6. Conclusion and Additional Resources

Congratulations! You have now learned how to create a simple Spring Boot application and how to push the code to a GitHub repository. This process is an important step in laying the foundation for backend development.

You can find additional materials and references through the following links:

I hope this tutorial was helpful. For those wishing to advance further, challenge yourselves to work on various projects utilizing Spring Boot and Git!