Spring Boot has taken the Spring framework to the next level. It has drastically reduced the configuration and setup time required for Spring projects. You can set up a project with almost zero configuration and start building the things that actually matter to your application.
If you are new to Spring Boot and want to get started with it quickly, then this blog post is for you.
Video Tutorial
This tutorial is explained in detail in the video tutorial below:
What We’ll Build
We are building a simple User Management Application which has the following CRUD Rest APIs:
- GET /api/users - Retrieves all users
- GET /api/users/{id} - Retrieves a specific user by id
- POST /api/users - Creates a new user
- PUT /api/users/{id} - Updates an existing user
- DELETE /api/users/{id} - Deletes a user by id
High-Level Architecture of Spring Boot Project
1. Creating a Spring Boot Application
There are many ways to create a Spring Boot application. You can refer to the following articles to create a Spring Boot application:
- Create Spring Boot Project With Spring Initializer
- Create Spring Boot Project in Spring Tool Suite [STS]
2. Maven Dependencies
Add the following dependencies in your pom.xml
file:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>com.mysql</groupId>
<artifactId>mysql-connector-j</artifactId>
<scope>runtime</scope>
</dependency>
Explanation:
- spring-boot-starter-data-jpa: Provides support for JPA-based data access and ORM.
- spring-boot-starter-web: Provides support for building web, including RESTful, applications using Spring MVC.
- mysql-connector-j: MySQL JDBC driver for connecting to MySQL databases.
3. Configuring MySQL Database
Configure the database URL, username, and password in the src/main/resources/application.properties
file to establish a connection with the database on startup:
spring.datasource.url = jdbc:mysql://localhost:3306/usersDB?useSSL=false
spring.datasource.username = root
spring.datasource.password = root
# Hibernate Properties
# The SQL dialect makes Hibernate generate better SQL for the chosen database
spring.jpa.properties.hibernate.dialect = org.hibernate.dialect.MySQLDialect
# Hibernate ddl auto (create, create-drop, validate, update)
spring.jpa.hibernate.ddl-auto = update
Explanation:
- spring.datasource.url: JDBC URL for MySQL database.
- spring.datasource.username: Username for MySQL database.
- spring.datasource.password: Password for MySQL database.
- spring.jpa.properties.hibernate.dialect: Hibernate dialect for MySQL.
- spring.jpa.hibernate.ddl-auto: update - Hibernate will automatically create the tables.
Don’t forget to change the spring.datasource.username
and spring.datasource.password
as per your MySQL installation. Also, create a database named usersDB in MySQL before proceeding to the next section.
You don’t need to create any tables. The tables will automatically be created by Hibernate from the User entity that we will define in the next step. This is made possible by the property spring.jpa.hibernate.ddl-auto = update
.
4. Create User JPA Entity
Create a User model or domain class with the following fields: id, firstName, lastName, and email.
package net.javaguides.springboot.entity;
import jakarta.persistence.*;
@Entity
@Table(name = "users")
public class User {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private long id;
@Column(name = "first_name")
private String firstName;
@Column(name = "last_name")
private String lastName;
@Column(name = "email")
private String email;
public User() {
}
public User(String firstName, String lastName, String email) {
this.firstName = firstName;
this.lastName = lastName;
this.email = email;
}
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
}
Explanation:
- @Entity: Marks the class as a persistent Java class.
- @Table: Provides the details of the table that this entity will be mapped to.
- @Id: Defines the primary key.
- @GeneratedValue: Defines the primary key generation strategy. In this case, it's an Auto Increment field.
- @Column: Defines the properties of the column that will be mapped to the annotated field. You can define several properties like name, length, nullable, updateable, etc.
5. Define UserRepository
Create a UserRepository to access User data from the database.
package net.javaguides.springboot.repository;
import org.springframework.data.jpa.repository.JpaRepository;
import net.javaguides.springboot.entity.User;
public interface UserRepository extends JpaRepository<User, Long> {
}
Explanation:
- JpaRepository: This repository provides CRUD operations on the entity. It contains methods for standard CRUD operations and allows you to create custom query methods.
6. Creating Custom Business Exception
Define custom exceptions to handle specific application errors. In this case, a ResourceNotFoundException is thrown whenever a User with a given ID is not found in the database.
package net.javaguides.springboot.exception;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ResponseStatus;
@ResponseStatus(value = HttpStatus.NOT_FOUND)
public class ResourceNotFoundException extends RuntimeException {
private static final long serialVersionUID = 1L;
public ResourceNotFoundException(String message) {
super(message);
}
}
Explanation:
- @ResponseStatus: Marks a method or exception class with the status code and reason that should be returned.
- RuntimeException: The superclass of exceptions that can be thrown during the normal operation of the Java Virtual Machine.
7. Creating UserController - Building CRUD Rest APIs
Create the REST APIs for creating, retrieving, updating, and deleting a User.
package net.javaguides.springboot.controller;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import net.javaguides.springboot.entity.User;
import net.javaguides.springboot.exception.ResourceNotFoundException;
import net.javaguides.springboot.repository.UserRepository;
@RestController
@RequestMapping("/api/users")
public class UserController {
@Autowired
private UserRepository userRepository;
// Get all users
@GetMapping
public List<User> getAllUsers() {
return this.userRepository.findAll();
}
// Get user by id
@GetMapping("/{id}")
public User getUserById(@PathVariable long id) {
return this.userRepository.findById(id)
.orElseThrow(() -> new ResourceNotFoundException("User not found with id :" + id));
}
// Create user
@PostMapping
public User createUser(@RequestBody User user) {
return this.userRepository.save(user);
}
// Update user
@PutMapping("/{id}")
public User updateUser(@RequestBody User user, @PathVariable long id) {
User existingUser = this.userRepository.findById(id)
.orElseThrow(() -> new ResourceNotFoundException("User not found with id :" + id));
existingUser.setFirstName(user.getFirstName());
existingUser.setLastName(user.getLastName());
existingUser.setEmail(user.getEmail());
return this.userRepository.save(existingUser);
}
// Delete user by id
@DeleteMapping("/{id}")
public ResponseEntity<User> deleteUser(@PathVariable long id) {
User existingUser = this.userRepository.findById(id)
.orElseThrow(() -> new ResourceNotFoundException("User not found with id :" + id));
this.userRepository.delete(existingUser);
return ResponseEntity.ok().build();
}
}
Explanation:
- @RestController: Indicates that the class is a REST controller.
- @RequestMapping: Maps HTTP requests to handler methods of MVC and REST controllers.
- @Autowired: Used for automatic dependency injection.
- @GetMapping: Handles HTTP GET requests.
- @PostMapping: Handles HTTP POST requests.
- @PutMapping: Handles HTTP PUT requests.
- @DeleteMapping: Handles HTTP DELETE requests.
- @PathVariable: Used to extract values from the URI.
- @RequestBody: Used to bind the HTTP request/response body with a domain object.
8. Running the Application
We have successfully developed all the CRUD Rest APIs for the User model. Now it's time to deploy our application in a servlet container (embedded Tomcat).
Two ways we can start the standalone Spring Boot application:
- From the root directory of the application, type the following command to run it:
$ mvn spring-boot:run
- From your IDE, run the
SpringBootCrudRestApplication.main()
method as a standalone Java class that will start the embedded Tomcat server on port 8080. Then point your browser to http://localhost:8080/.
9. Demo
The demo of this tutorial is covered in the YouTube video tutorial below:
10. Conclusion
Congratulations! We successfully built a Restful CRUD API using Spring Boot, MySQL, JPA, and Hibernate.
You can find the source code for this tutorial on my GitHub repository. Feel free to clone the repository and build upon it.
Thank you for reading. Please ask any questions in the comment section below.
← Back to Spring Boot Tutorial
Very useful and informative tutorial.
ReplyDeletehow i can coonect my mysql connection in mysql workbench
ReplyDeletewhat is hostname in mysql
ReplyDeletelocalhost. Watch video tutorial, you will get everything that you want.
DeleteWhen I run this, I get an error saying "Error creating bean with name 'entityManagerFactory'"
ReplyDeleteDo you have any idea what this means? I didn't change anything in the provided code except for the username and password for my local mysql server
Make sure that MySQL server is running in your machine and you have configured the same in spring boot project. Typical we get this error when spring boot don't able connect to MySQL server due to configuration issue.
DeleteHey Ramesh. Great work once again. I am understanding things on a high level but when runtime exceptions arise it is hard for me to find the underlying problems that are causing the exceptions. What do you think I should do? Should I read the documentation on SPring core or is that overkill? How about your spring core blog? WOuld that be enough for me to understand how spring boot works under the hood?
ReplyDeleteYeah. You can learn Spring core from my blog which will lead you to understand spring boot internals and how spring boot works behind the scene.
Deleteok Ramesh ty for ur advice please continue posting videos on youtube its very helpful
DeleteSure buddy. Connect with me social media.
Deletejava.sql.SQLNonTransientConnectionException: CLIENT_PLUGIN_AUTH is required
ReplyDeletejava.sql.SQLNonTransientConnectionException: CLIENT_PLUGIN_AUTH is required
Caused by: com.mysql.cj.exceptions.UnableToConnectException: CLIENT_PLUGIN_AUTH is required
Hi Ramesh
ReplyDeleteI am getting the below error
java.lang.NullPointerException: Cannot invoke "com.tool.springboot.repository.UserRepository.save(Object)" because "this.userRepository" is null