Building an Application with Java Spring Boot / Spring Framework

This guide is meant to give you a quick taste of Spring Boot. you want to create your own Spring Boot-based project, visit Spring Initializr, fill in your project details, pick your options, and download a bundled up project as a zip file.

What You Will build

You will build a simple web application with Spring Boot and add some useful services to it.

What You Need

  • Install Intellij IDEA
  • Java 21
  • Gradle 7.5+ or Maven 3.5+
  • Install MySQL and setup your database

Starting with Spring Initializr

To manually initialize the project:

  1. Navigate to https://start.spring.io. This service pulls in all the dependencies you need for an application and does most of the setup for you.
  2. Choose either Gradle or Maven and the language you want to use. This guide assumes that you chose Java.
  3. Click Dependencies and select Spring Web and Spring Data JPA and choose one of your database driver:
    • PostgreSQL Driver
    • MariaDB Driver
    • MySQL Driver (this guide is using this)
  4. Click Generate.
  5. Download the resulting ZIP file, which is an archive of a web application that is configured with your choices.
java-spring-1

Project Installation

  1. Unzip it and open with IntelliJ
  2. Ensure your Project Structure in Intellij is using Java 21
java-spring-2
  1. Please wait for a few minutes or seconds. Intellij will download all the project dependencies.
  2. Check your intellij looks ready to run with play button like below.
java-spring-3
  1. Create table in mysql
CREATE TABLE user_data (
    id int NOT NULL AUTO_INCREMENT PRIMARY KEY,
    full_name varchar(255),
    nick_name varchar(255),
    email varchar(255),
    address varchar(255),
    city varchar(255),
    created_at datetime DEFAULT CURRENT_TIMESTAMP,
    created_by varchar(255) NOT NULL,
  	updated_at datetime DEFAULT CURRENT_TIMESTAMP,
  	updated_by varchar(255) NOT NULL
);

Create a Simple Web Application

in your pom.xml add this dependency

   <dependency>
      <groupId>org.springdoc</groupId>
      <artifactId>springdoc-openapi-starter-webmvc-ui</artifactId>
      <version>2.8.4</version>
   </dependency>

  <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-validation</artifactId>
  </dependency>

or add this dependency in your build.gradle

implementation 'org.springdoc:springdoc-openapi-starter-webmvc-ui:2.8.4'
implementation 'org.springframework.boot:spring-boot-starter-validation'

and then you can install it using mvn install or gradle build.

or using intellij click this button
using maven

java-spring-4

using gradle

java-spring-5

now setup your application.properties

spring.datasource.url=jdbc:mysql://localhost:3306/<your_database>
spring.datasource.username=<your_username>
spring.datasource.password=<your_password>
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver

spring.datasource.hikari.minimum-idle=2
spring.datasource.hikari.maximum-pool-size=3

spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.MySQL8Dialect
spring.jpa.show-sql=true
spring.jpa.hibernate.ddl-auto=update

# if you have been using postman for interacting with API, this is an alternative
# https://springdoc.org/
springdoc.swagger-ui.enabled=true
springdoc.api-docs.enabled=true

Now you can create a web controller for a simple web application, as the following listing (from src/main/java/com/example/introduction/UserController.java) shows:

@RestController
public class UserController {

	@GetMapping("/user")
	public String getAllUser() {
		return "Greetings from Spring Boot!";
	}

}

Click the play button here (IntroductionApplication.java)

java-spring-6

and should be running well like this

java-spring-7

Go to here http://localhost:8080/swagger-ui/index.html and you should see like this

java-spring-8

and you can use this swagger ui as your API documentation and interact with your API
click button Try it out

java-spring-9

click button Execute

java-spring-10

the result are like this (see the response body)

java-spring-11

Create Entity and JPA Repository

Now you can create a entity, as the following listing (from src/main/java/com/example/introduction/UserData.java) shows:

@Entity
@Table(name = "user_data")
public class UserData {

    @Id
    @GeneratedValue(strategy= GenerationType.IDENTITY)
    @Column(name = "id")
    public Integer id;

    @Column(name = "full_name")
    public String fullName;

    @Column(name = "nick_name")
    public String nickName;

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

    @Column(name = "address")
    public String address;

    @Column(name = "city")
    public String city;

    @CreationTimestamp
    @Column(name = "created_at")
    public OffsetDateTime createdAt;

    @Column(name = "created_by")
    public String createdBy;

    @UpdateTimestamp
    @Column(name = "updated_at")
    public OffsetDateTime updatedAt;

    @Column(name = "updated_by")
    public String updatedBy;
}

Now you can create a repository, as the following listing (from src/main/java/com/example/introduction/UserDataRepository.java) shows:

@Repository
public interface UserDataRepository extends JpaRepository<UserData, Integer> {

    Optional<UserData> findByEmail(String email);

}

and create the DTO for create user request body

@JsonIgnoreProperties(ignoreUnknown = true)
public class CreateUserRequest {
    @NotNull
    @NotBlank
    private String fullName;

    @NotNull
    @NotBlank
    private String nickName;

    @NotNull
    @NotBlank
    private String email;

    @NotNull
    @NotBlank
    private String address;

    @NotNull
    @NotBlank
    private String city;

    // Getters and Setters
    public String getFullName() {
        return fullName;
    }

    public void setFullName(String fullName) {
        this.fullName = fullName;
    }

    public String getNickName() {
        return nickName;
    }

    public void setNickName(String nickName) {
        this.nickName = nickName;
    }

    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }

    public String getAddress() {
        return address;
    }

    public void setAddress(String address) {
        this.address = address;
    }

    public String getCity() {
        return city;
    }

    public void setCity(String city) {
        this.city = city;
    }
}

and create a configuration class (src/main/java/com/example/introduction/config/AppConfig.java)

@Configuration
public class AppConfig {

    @Bean
    public LocalValidatorFactoryBean validator() {
        return new LocalValidatorFactoryBean();
    }

}

Let's update the controller code

@RestController
public class UserController {

    private final UserDataRepository userDataRepository;

    @Autowired
    public UserController(UserDataRepository userDataRepository) {
        this.userDataRepository = userDataRepository;
    }

    @GetMapping("/user")
    public List<UserData> getAllUser() {
        return userDataRepository.findAll();
    }

    @GetMapping("/user/{userId}")
    public UserData getUserById(@PathVariable Integer userId) {
        Optional<UserData> userData = userDataRepository.findById(userId);
        return userData.orElse(null);
    }

    @GetMapping("/user-by-email")
    public UserData getUserByEmail(@RequestParam String email) {
        Optional<UserData> userData = userDataRepository.findByEmail(email);
        return userData.orElse(null);
    }

    @PostMapping("/user")
    public UserData createUser(@Valid @RequestBody CreateUserRequest request) {
        UserData userData = new UserData();
        userData.fullName = request.getFullName();
        userData.nickName = request.getNickName();
        userData.email = request.getEmail();
        userData.address = request.getAddress();
        userData.city = request.getCity();
        userData.createdBy = "admin";
        userData.updatedBy = "admin";
        return userDataRepository.saveAndFlush(userData);
    }

}

and re run the app by click the play button.

now open again your swagger-ui and expand the POST /user and execute it

java-spring-12 java-spring-13

and then use the GET /user/{userId}

java-spring-14

and then use the GET /user-by-email?email=string

java-spring-15

and then use the GET /user

java-spring-16

Summary

Congratulations! You have just developed a Java Spring application that is bound to a MySQL database and is ready to use! And you have taste in how to develop REST API spring boot applications.

Challenge

I'm giving you to challenge to explore more about java

  1. You can update class UserData from using access modifier public to private and then create setters / getters
// code snippet

@Entity
@Table(name = "user_data")
public class UserData {

    @Id
    @GeneratedValue(strategy= GenerationType.IDENTITY)
    @Column(name = "id")
    private Integer id;

    @Column(name = "full_name")
    private String fullName;

    ...

    // setters/getters
    public Integer getId() {
        return id;
    }

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

    public String getFullName() {
        return fullName;
    }

    public void setFullName(String fullName) {
        this.fullName = fullName;
    }

    ...

and you can create java class constructors

// code snippet

@Entity
@Table(name = "user_data")
public class UserData {
  ...

  // constructor
  public UserData(String fullName, String nickName, ...) {
      this.fullName = fullName;
      this.nickName = nickName;
      ...
  }
}
  1. You can use Java Record for class CreateUserRequest
// code snippet
public record CreateUserRequest (String fullName, String nickName, ...) {}
  1. You can use ResponseEntity in UserController.java you can use ResponseEntity in java like code snippet below
@GetMapping("/user/{userId}")
public ResponseEntity<UserData> getUserById(@PathVariable Integer userId) {
    Optional<UserData> userData = userDataRepository.findById(userId);
    return ResponseEntity.ok(userData.orElse(null));
}

Hint for you

You can use IntelliJ features to generate getter / setter and constructor

java-spring-17

I hope you are now understand how to use Java Spring Boot to create REST API Service.
Thank you for reading and your attention. See you soon on the next post.

If you want to see the codebase please visit this GitHub: java-spring-introduction

Learn more

Go learn more about