Spring Boot Backend Development Course, Practicing Database Manipulation with SQL Statements

Spring Boot is a powerful framework for developing web applications based on Java. In this course, we will cover backend development using Spring Boot and learn how to manipulate databases using SQL statements.

Table of Contents

  • 1. Introduction to Spring Boot
  • 2. Project Setup
  • 3. Database Integration
  • 4. Manipulating Data with SQL Statements
  • 5. Implementing CRUD
  • 6. Testing and Deployment
  • 7. Conclusion

1. Introduction to Spring Boot

Spring Boot is a lightweight application development framework based on the Spring framework. It simplifies configuration and helps to easily build stand-alone applications.

Characteristics of Spring Boot include:

  • Auto Configuration
  • Embedded Web Server
  • Production Ready

2. Project Setup

The best way to create a Spring Boot project is to use the Spring Initializr website. Here, you can enter project metadata and add the necessary dependencies.

1. Visit Spring Initializr: https://start.spring.io/
2. Select Project: Maven Project or Gradle Project
3. Language: Java
4. Group: com.example
5. Artifact: demo
6. Dependencies: Spring Web, Spring Data JPA, H2 Database

3. Database Integration

To integrate a database with Spring Boot, you need to set database information in the application.properties file.

# H2 Database Configuration
spring.h2.console.enabled=true
spring.datasource.url=jdbc:h2:mem:testdb
spring.datasource.driverClassName=org.h2.Driver
spring.datasource.username=sa
spring.datasource.password=password
spring.jpa.database-platform=org.hibernate.dialect.H2Dialect

4. Manipulating Data with SQL Statements

We will learn how to manipulate data in the database using SQL statements. Basic SQL statements include SELECT, INSERT, UPDATE, DELETE.

4.1 SELECT Statement

The SELECT statement is used to retrieve data from the database. For example, you can use the following query to retrieve all users:

SELECT * FROM users;

4.2 INSERT Statement

The INSERT statement is used to add new data to the database. The following query adds a new user:

INSERT INTO users (username, email) VALUES ('testuser', 'test@example.com');

4.3 UPDATE Statement

The UPDATE statement is used to modify existing data. An example of changing a specific user’s email is as follows:

UPDATE users SET email = 'newemail@example.com' WHERE username = 'testuser';

4.4 DELETE Statement

The DELETE statement is used to delete data from the database. The query to delete a user is as follows:

DELETE FROM users WHERE username = 'testuser';

5. Implementing CRUD

Implementing CRUD (Create, Read, Update, Delete) functionality is essential for database manipulation. We will set up Repository, Service, and Controller to implement CRUD in Spring Boot.

5.1 Repository

The Repository defines interactions with the database. Using JPA, you create an interface, and basic CRUD methods are automatically provided:

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

public interface UserRepository extends JpaRepository<User, Long> {
    // Additional query methods can be defined here.
}

5.2 Service

The Service handles business logic. It injects the Repository to implement the necessary functionalities:

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class UserService {
    @Autowired
    private UserRepository userRepository;

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

    // Add other CRUD methods
}

5.3 Controller

The Controller handles HTTP requests. It sets up appropriate endpoints to manage communication with the client:

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/api/users")
public class UserController {
    @Autowired
    private UserService userService;

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

    // Add other CRUD endpoints
}

6. Testing and Deployment

Testing is essential for discovering and fixing bugs in the application. In Spring Boot, you can perform unit testing using JUnit.

import org.junit.jupiter.api.Test;
import static org.assertj.core.api.Assertions.assertThat;

public class UserServiceTest {
    @Test
    public void testCreateUser() {
        // User creation test code
    }
}

7. Conclusion

In this course, we explored backend development using Spring Boot and how to manipulate databases using SQL statements. Through this course, we hope you will be equipped to build practical web applications.

Spring Boot Backend Development Course, What is RDB

Today, we will explore relational databases (RDB) that are essential to understand when doing backend development using Spring Boot. Databases are one of the most important parts of software projects, and RDB is widely used globally as a database model. In this article, we will explain the concepts, characteristics, and integration methods of RDB in detail.

1. What is a Relational Database (RDB)?

A relational database is a type of database that organizes and stores data in tabular form. Each table consists of rows and columns, and data can be linked through the relationships between tables. RDB uses Structured Query Language (SQL) to define and manipulate data.

1.1 History of RDB

In the early 1960s, Edgar F. Codd proposed the relational model for databases, laying the foundation for RDB. In the 1970s, IBM developed a relational database system based on SQL, leading to the evolution of RDBMS (Relational Database Management System). Today, various RDBMS such as MySQL, PostgreSQL, Oracle Database, and Microsoft SQL Server are in use.

1.2 Components of RDB

  • Table: The basic unit where data is stored. Each table contains data related to a specific subject.
  • Row: Represents each data record in the table. Each row corresponds to specific data.
  • Column: Defines the attributes belonging to each row. For example, in a user table, ‘name’, ’email’, etc. can be defined as columns.
  • Primary Key: A single column or a combination of columns that uniquely identifies each row.
  • Foreign Key: A column that establishes a relationship between two tables. It references the primary key of another table.

2. Main Features of RDB

Relational databases have several features that have made RDB the standard for data management.

  • Data Integrity: Ensures the accuracy and consistency of data. For example, foreign key constraints can maintain the integrity of data relationships.
  • Normalization: The process of structuring data to minimize redundancy and maintain integrity.
  • ACID Properties: Guarantees the atomicity, consistency, isolation, and durability of transactions, enhancing database stability.
  • SQL Support: Data retrieval, insertion, modification, and deletion can be performed through SQL. SQL is the standard query language for relational databases.
  • Implementation of Business Rules: RDB allows the implementation of business rules at the database level. For example, constraints can be set to only allow data that meets specific conditions to be entered.

3. Spring Boot and RDB

Spring Boot is a Java-based framework that supports fast and easy application development. This framework also simplifies the integration with RDBMS. Here’s how to connect to an RDB using Spring Boot.

3.1 Adding Spring Boot Dependencies

When creating a Spring Boot project, you need to add dependencies suitable for the RDBMS you are using in the `pom.xml` or `build.gradle` file. For example, if you are using MySQL, you can add the following dependency.



    mysql
    mysql-connector-java
    8.0.26

3.2 Configuring the Data Source

In Spring Boot, you must configure the information for database connection in the application.properties file. Here is an example of configuring a MySQL database.


spring.datasource.url=jdbc:mysql://localhost:3306/your_database
spring.datasource.username=your_username
spring.datasource.password=your_password
spring.jpa.hibernate.ddl-auto=update
spring.jpa.show-sql=true

3.3 Creating Entity Classes

Create entity classes that map to database tables. For example, you can define a User entity to store user information as follows.


import javax.persistence.*;

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

    @Column(name = "username")
    private String username;

    @Column(name = "email")
    private String email;

    // Getters and setters
}

3.4 Creating Repository Interfaces

To handle CRUD (Create, Read, Update, Delete) operations for the entities, you can define repository interfaces using Spring Data JPA.


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

public interface UserRepository extends JpaRepository {
    User findByUsername(String username);
}

3.5 Creating Services and Controllers

Create service classes to handle business logic and use them to create controllers that provide RESTful APIs. For example:


import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

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

    @Autowired
    private UserService userService;

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

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

    // Other methods
}

4. Use Cases of RDB

Relational databases are used in various fields. Some key use cases include:

  • Security-related Data Recording: Used to store user personal information or transaction data safely and accurately.
  • eCommerce Sites: Efficiently manages various data such as products, customers, and orders by storing them in relational databases.
  • Financial Management: Ideal for structurally storing and managing tax, revenue, and expenditure information.
  • Medical Record Management: Effectively manages patient medical records and treatment histories.

5. Conclusion

RDB is very useful as a database management system that efficiently stores and manages data while maintaining data integrity and consistency. Using Spring Boot simplifies the integration with relational databases, allowing for rapid application development. I hope this course enhances your understanding of the concepts of RDB and its integration with Spring Boot.

Spring Boot Backend Development Course, What is ORM

Spring Boot is a framework that helps develop Java-based web applications easily. In this tutorial, we will cover one of the key concepts of Spring Boot, which is ORM (Object-Relational Mapping). ORM is a technology that simplifies interaction between the object-oriented programming language Java and relational databases. In this article, we will delve deeply into various topics such as the definition of ORM, its advantages, usage, integration with Spring Boot, and more.

Definition of ORM

ORM is a technology that provides mapping between objects used in object-oriented programming languages and tables used in relational databases. Simply put, ORM allows database data to be represented as objects in object-oriented languages. As a result, developers can interact with the database without the need to write SQL queries. Common implementations of ORM include Hibernate, JPA (Java Persistence API), and more.

History of ORM

The concept of ORM can be traced back to the late 1980s. It first emerged to provide a concise interaction with databases along with the advancement of object-oriented languages. Gradually, ORM technologies gained recognition for their utility and productivity and became widely used in various frameworks and libraries. In the Java ecosystem, JPA and Hibernate have solidified their position as the leading implementations of ORM.

Advantages of ORM

Using ORM provides several advantages:

  • Increased Productivity: By using ORM, developers do not need to write SQL queries directly, which greatly enhances development productivity.
  • Easier Maintenance: Even if the database structure changes, due to object mapping, less code modification is needed, making maintenance easier.
  • Object-Oriented Development: The representation of database data as objects allows for maximum utilization of the advantages of object-oriented programming.
  • Database Independence: Using ORM enables the development of applications independently of specific database vendors.

Disadvantages of ORM

Of course, ORM is not without its disadvantages. Here are some drawbacks of using ORM:

  • Performance Issues: Since ORM automatically generates SQL, performance issues can arise. Incorrect query generation or unnecessary JOINs can be problematic.
  • Limitations of Abstraction: There may be cases where the abstraction provided by ORM cannot accurately represent all data, and there may still be a need to use SQL for complex queries.
  • Learning Curve: There can be a learning curve for users who are new to ORM frameworks. This is especially true in cases with complex mappings.

Using ORM in Spring Boot

Spring Boot uses JPA as its default ORM. JPA is a set of interfaces that define the mapping between Java objects and relational databases. In Spring Boot, you can easily apply ORM by adding JPA as a dependency.

JPA and Hibernate

JPA is a standard interface, and Hibernate is an ORM framework that implements this standard interface. By using Hibernate, you can manage interactions with the database through JPA, allowing for easy execution of CRUD (Create, Read, Update, Delete) operations on the database. Now, let’s look at actual code examples to see how to use JPA and Hibernate.

Setting Up the Environment

First, to use JPA and Hibernate in a Spring Boot project, you need to add the following dependencies. Add the following to the pom.xml file using Maven:


    <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>
    

Defining the Entity Class

Next, define the entity class that will be mapped to the database. For example, let’s create an entity class called User:


    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
    }
    

Writing the Repository Interface

Write a repository interface to perform CRUD operations:


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

    public interface UserRepository extends JpaRepository<User, Long> {
    }
    

Writing the Service Class

Now, you can implement business logic through the service class:


    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 User createUser(User user) {
            return userRepository.save(user);
        }

        public List<User> getAllUsers() {
            return userRepository.findAll();
        }
    }
    

Writing the Controller Class

Finally, write a controller class to provide the REST API:


    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.http.ResponseEntity;
    import org.springframework.web.bind.annotation.*;

    import java.util.List;

    @RestController
    @RequestMapping("/api/users")
    public class UserController {
        @Autowired
        private UserService userService;

        @PostMapping
        public ResponseEntity<User> createUser(@RequestBody User user) {
            return ResponseEntity.ok(userService.createUser(user));
        }

        @GetMapping
        public ResponseEntity<List<User>> getAllUsers() {
            return ResponseEntity.ok(userService.getAllUsers());
        }
    }
    

Conclusion

In this tutorial, we explored what ORM is in Spring Boot and how to interact with databases through it. ORM is a powerful tool that enhances development productivity and simplifies maintenance. The method of interacting with the database using JPA and Hibernate is relatively straightforward, and these technologies make backend development much easier.

In future tutorials, we will delve into more examples and advanced features of ORM. Please look forward to more content on backend development using Spring Boot!

Spring Boot Backend Development Course, Implementing Login and Logout with OAuth2, Obtaining Tokens

In recent years, the security and user authentication methods of web applications have changed dramatically. In particular, OAuth2 has established itself as the standard for handling user authentication in many web services. This course will detail how to implement login and logout using OAuth2 with Spring Boot, as well as the token issuance process. Through this article, you will learn the basic principles of OAuth2 and gain the skills needed to build real applications.

1. What is OAuth2?

OAuth2 is a protocol for user authentication that allows users to grant access without providing their information to third-party services. This enables apps or services to access the user’s resources. The main components of OAuth2 are as follows:

  • User (Resource Owner): The entity that protects and manages their information.
  • Client: An application that seeks to access resources on behalf of the user.
  • Resource Server: The server that provides protected resources.
  • Authorization Server: The server that handles user authentication and issues access tokens to the client.

2. What is Spring Boot?

Spring Boot is a project based on Java’s Spring Framework that helps in quickly developing applications. Spring Boot offers the following advantages:

  • Simplified configuration: Thanks to various defaults, you can get started quickly without complex configurations.
  • Auto-configuration: You can easily add the necessary libraries for automatic configuration.
  • Starter packages: These provide starter packages that combine multiple dependencies and configurations to speed up development.

3. Preparing to Build an OAuth2 Login System

3.1 Project Setup

To start a Spring Boot project, use Spring Initializr to create a basic project. Add the following dependencies:

  • Spring Web
  • Spring Security
  • OAuth2 Client
  • Spring Data JPA
  • H2 Database (for development)

3.2 Project Structure

        /src
        └── main
            ├── java
            │   └── com
            │       └── example
            │           └── oauth2demo
            │               ├── controller
            │               ├── model
            │               ├── repository
            │               ├── security
            │               └── service
            └── resources
                ├── application.properties
                └── static
    

3.3 Configuring application.properties

To use OAuth2, configure as below. I will use Google OAuth2 as an example:

        spring.security.oauth2.client.registration.google.client-id=YOUR_CLIENT_ID
        spring.security.oauth2.client.registration.google.client-secret=YOUR_CLIENT_SECRET
        spring.security.oauth2.client.registration.google.redirect-uri={baseUrl}/login/oauth2/code/{registrationId}
        spring.security.oauth2.client.registration.google.scope=profile, email
        spring.security.oauth2.client.provider.google.authorization-uri=https://accounts.google.com/o/oauth2/auth
        spring.security.oauth2.client.provider.google.token-uri=https://oauth2.googleapis.com/token
        spring.security.oauth2.client.provider.google.user-info-uri=https://www.googleapis.com/oauth2/v3/userinfo
    

4. Spring Security Configuration

Spring Security is used to manage authentication and authorization. Below is a basic security configuration example:

    import org.springframework.context.annotation.Bean;
    import org.springframework.context.annotation.Configuration;
    import org.springframework.security.config.annotation.web.builders.HttpSecurity;
    import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
    import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;

    @Configuration
    @EnableWebSecurity
    public class SecurityConfig extends WebSecurityConfigurerAdapter {
        @Override
        protected void configure(HttpSecurity http) throws Exception {
            http
                .authorizeRequests()
                .anyRequest().authenticated()
                .and()
                .oauth2Login();
        }
    }
    

5. Retrieving User Information

Once the user has completed the login, the client application can obtain the authentication information. To fetch user’s information, implement the service below:

    import org.springframework.security.core.Authentication;
    import org.springframework.security.oauth2.core.user.OAuth2User;
    import org.springframework.stereotype.Service;

    @Service
    public class UserService {
        public String getCurrentUserName(Authentication authentication) {
            OAuth2User oauth2User = (OAuth2User) authentication.getPrincipal();
            return oauth2User.getAttribute("name");
        }
    }
    

6. Implementing Logout

Logout is also a common requirement. You can implement a simple logout feature using the configuration below:

    http
        .logout()
        .logoutSuccessUrl("/login")
        .invalidateHttpSession(true)
        .clearAuthentication(true);
    

7. Running and Testing the Application

After completing all configurations, run the application and access http://localhost:8080 in your web browser. If configured correctly, the Google login screen will appear. You will also be able to view a screen that retrieves the user’s name after logging in.

8. Conclusion

In this course, we explored how to implement login and logout functions based on OAuth2 using Spring Boot. OAuth2 is a widely used authentication method in modern web applications, and we have seen how easily it can be configured using Spring Boot. We hope to build a more secure and convenient user authentication system by adding more advanced features in the future.

Additional Resources

If you would like more information, please refer to the links below:

Spring Boot Backend Development Course, Adding Approved URI to OAuth Service

Modern web applications require user authentication and authorization management. OAuth 2.0 is one of the popular protocols for such authentication, allowing users to securely access services without exposing their credentials to third-party applications. This tutorial will guide you step-by-step on how to add authorized URIs to an OAuth service using Spring Boot.

1. Overview of OAuth

OAuth 2.0 is a protocol for user authentication, widely used primarily in web applications. When using OAuth, users receive a token that allows them to access other services without providing their login information. OAuth 2.0 supports many different authentication providers, each requiring a URI to process authentication requests.

2. Integrating Spring Boot with OAuth

Using Spring Boot makes it easy to implement OAuth 2.0 authentication. This process aims to set up an OAuth 2.0 client using Spring Security and add authorized URIs to the service.

2.1. Project Setup

To start a Spring Boot project, add the dependencies for spring-boot-starter-web and spring-boot-starter-security. Additionally, you will also need the dependency for spring-boot-starter-oauth2-client to use OAuth 2.0 clients.

    
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-security</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-oauth2-client</artifactId>
    </dependency>

3. Understanding the Authorized URI

In OAuth 2.0, the authorized URI is the address where users will be redirected after authentication. This URI is specified when registering the client, and the authentication service redirects to this URI to send the response after user authentication. It may include an access token along with user information.

4. Adding Authorized URI in Spring Boot

4.1. Configuring application.yml

In Spring Boot, you can set up OAuth client properties through the application.yml or application.properties file. Here is an example of configuring a Google OAuth 2.0 client.


spring:
  security:
    oauth2:
      client:
        registration:
          google:
            client-id: YOUR_CLIENT_ID
            client-secret: YOUR_CLIENT_SECRET
            scope: profile, email
            redirect-uri: "{baseUrl}/login/oauth2/code/{registrationId}"
        provider:
          google:
            authorization-uri: https://accounts.google.com/o/oauth2/auth
            token-uri: https://oauth2.googleapis.com/token
            user-info-uri: https://www.googleapis.com/oauth2/v3/userinfo

4.2. Configuring Web Security

To use OAuth 2.0 authentication, you need to add web security configuration. The following settings ensure that only authenticated users can access certain paths.


import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;

@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
            .authorizeRequests()
                .antMatchers("/", "/login").permitAll() // Paths accessible without login
                .anyRequest().authenticated() // All other requests require authentication
                .and()
            .oauth2Login(); // OAuth 2.0 login
    }
}

4.3. Testing the Authorized URI

You can now run Spring Boot and navigate to http://localhost:8080 to test the OAuth login. A Google login button will appear, allowing users to authenticate.

5. Monitoring the Authorized URI

It is important to understand how the authorized URI works in an OAuth 2.0 application. Let’s look at several issues that may arise in this process and their solutions.

5.1. Redirection Errors

If the redirection URI is set incorrectly, users may not be redirected to the appropriate page after authentication. In such cases, you need to ensure that the authorized redirection URI is entered correctly when registering the client. For example:

    
    redirect-uri: http://localhost:8080/login/oauth2/code/google

5.2. Scope Issues

Problems can also occur if the requested scopes are set incorrectly. If the scopes are set wrong, the authentication may fail, so pay attention to scope settings.

6. Implementing Additional Features

Now that we have set the basic OAuth 2.0 elements, we can implement features that display additional information after user authentication or control conditional access rights. For instance, let’s look at how to retrieve user profile information and display it on a web page.

6.1. Fetching User Information


import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;

@Controller
public class UserController {

    @GetMapping("/user")
    public String user(@AuthenticationPrincipal OAuth2AuthenticationToken authentication, Model model) {
        model.addAttribute("user", authentication.getPrincipal().getAttributes());
        return "user"; // Navigate to user.html
    }
}

6.2. Displaying User Information

To display user information, you can create a simple HTML template. Create a file named src/main/resources/templates/user.html and add the following code.


<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>User Information</title>
</head>
<body>

<h1>User Information</h1>
<ul>
    <li>Name: <span th:text="${user['name']}"></span></li>
    <li>Email: <span th:text="${user['email']}"></span></li>
</ul>

</body>
</html>

7. Conclusion

In this tutorial, we learned how to set up OAuth 2.0 authentication using Spring Boot and add authorized URIs. Implementing user authentication through the OAuth protocol provides a secure and convenient user experience. You can now add these functionalities to your projects and explore integrations with various APIs.

To fully utilize all features of OAuth 2.0, it’s advisable to refer to various libraries and documentation. For more in-depth information, please consult the official OAuth 2.0 documentation.