Prerequisites
Before we start, ensure you have the following:
- Java Development Kit (JDK) installed
- Apache Maven installed
- MySQL installed
- An IDE (such as IntelliJ IDEA, Eclipse, or VS Code) installed
Step 1: Setting Up the Project
1.1 Create a Spring Boot Project
-
Open Spring Initializr:
- Go to Spring Initializr in your web browser.
-
Configure Project Metadata:
- Project: Maven Project
- Language: Java
- Spring Boot: Select the latest version of Spring Boot
- Group: com.example
- Artifact: spring-boot-mysql-crud
- Name: spring-boot-mysql-crud
- Description: Spring Boot CRUD example with MySQL
- Package Name: com.example.springbootmysqlcrud
- Packaging: Jar
- Java Version: 17 (or your preferred version)
- Click
Next
.
-
Select Dependencies:
- Select the following dependencies:
- Spring Web
- Spring Data JPA
- MySQL Driver
- Spring Boot DevTools
- Click
Next
.
- Select the following dependencies:
-
Generate the Project:
- Click
Generate
to download the project zip file. - Extract the zip file to your desired location.
- Click
-
Open the Project in Your IDE:
- Open your IDE and import the project as a Maven project.
1.2 Project Structure
After importing the project, create packaging structure as per below structure:
spring-boot-mysql-crud ├── src │ ├── main │ │ ├── java │ │ │ └── com │ │ │ └── example │ │ │ └── springbootmysqlcrud │ │ │ ├── SpringBootMysqlCrudApplication.java │ │ │ ├── controller │ │ │ ├── model │ │ │ ├── repository │ │ │ └── service │ ├── main │ │ └── resources │ │ ├── application.properties │ └── test │ └── java │ └── com │ └── example │ └── springbootmysqlcrud │ └── SpringBootMysqlCrudApplicationTests.java └── pom.xml
Step 2: Configuring MySQL
2.1 Create a MySQL Database
- Open your MySQL client (MySQL Workbench, command line, etc.).
- Create a new database named
springbootdb
:CREATE DATABASE springbootdb;
2.2 Configure Spring Boot to Use MySQL
Open the application.properties
file located in the src/main/resources
directory and add the following configuration:
spring.datasource.url=jdbc:mysql://localhost:3306/springbootdb?useSSL=false&serverTimezone=UTC spring.datasource.username=root spring.datasource.password=yourpassword spring.jpa.hibernate.ddl-auto=update spring.jpa.show-sql=true
Replace yourpassword
with the password for your MySQL root
user.
Step 3: Creating the Entity
3.1 Create the Employee
Entity
In the model
package, create a new Java class named Employee
:
package com.example.springbootmysqlcrud.model; import jakarta.persistence.Entity; import jakarta.persistence.GeneratedValue; import jakarta.persistence.GenerationType; import jakarta.persistence.Id; @Entity public class Employee { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; private String firstName; private String lastName; private String email; // Getters and Setters 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; } }
Step 4: Creating the Repository
4.1 Create the EmployeeRepository
Interface
In the repository
package, create a new Java interface named EmployeeRepository
:
package com.example.springbootmysqlcrud.repository; import com.example.springbootmysqlcrud.model.Employee; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.stereotype.Repository; @Repository public interface EmployeeRepository extends JpaRepository<Employee, Long> { }
Step 5: Creating the Service
5.1 Create the EmployeeService
Interface
In the service
package, create a new Java interface named EmployeeService
:
package com.example.springbootmysqlcrud.service; import com.example.springbootmysqlcrud.model.Employee; import java.util.List; import java.util.Optional; public interface EmployeeService { List<Employee> getAllEmployees(); Optional<Employee> getEmployeeById(Long id); Employee saveEmployee(Employee employee); Employee updateEmployee(Employee employee); void deleteEmployee(Long id); }
5.2 Implement the EmployeeService
Interface
In the service
package, create a new Java class named EmployeeServiceImpl
:
package com.example.springbootmysqlcrud.service; import com.example.springbootmysqlcrud.model.Employee; import com.example.springbootmysqlcrud.repository.EmployeeRepository; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.util.List; import java.util.Optional; @Service public class EmployeeServiceImpl implements EmployeeService { @Autowired private EmployeeRepository employeeRepository; @Override public List<Employee> getAllEmployees() { return employeeRepository.findAll(); } @Override public Optional<Employee> getEmployeeById(Long id) { return employeeRepository.findById(id); } @Override public Employee saveEmployee(Employee employee) { return employeeRepository.save(employee); } @Override public Employee updateEmployee(Employee employee) { return employeeRepository.save(employee); } @Override public void deleteEmployee(Long id) { employeeRepository.deleteById(id); } }
Step 6: Creating the Controller
6.1 Create the EmployeeController
Class
In the controller
package, create a new Java class named EmployeeController
:
package com.example.springbootmysqlcrud.controller; import com.example.springbootmysqlcrud.model.Employee; import com.example.springbootmysqlcrud.service.EmployeeService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.*; import java.util.List; import java.util.Optional; @RestController @RequestMapping("/api/employees") public class EmployeeController { @Autowired private EmployeeService employeeService; @GetMapping public List<Employee> getAllEmployees() { return employeeService.getAllEmployees(); } @GetMapping("/{id}") public ResponseEntity<Employee> getEmployeeById(@PathVariable Long id) { Optional<Employee> employee = employeeService.getEmployeeById(id); return employee.map(ResponseEntity::ok).orElseGet(() -> ResponseEntity.notFound().build()); } @PostMapping public Employee createEmployee(@RequestBody Employee employee) { return employeeService.saveEmployee(employee); } @PutMapping("/{id}") public ResponseEntity<Employee> updateEmployee(@PathVariable Long id, @RequestBody Employee employeeDetails) { Optional<Employee> employeeOptional = employeeService.getEmployeeById(id); if (employeeOptional.isPresent()) { Employee employee = employeeOptional.get(); employee.setFirstName(employeeDetails.getFirstName()); employee.setLastName(employeeDetails.getLastName()); employee.setEmail(employeeDetails.getEmail()); return ResponseEntity.ok(employeeService.updateEmployee(employee)); } else { return ResponseEntity.notFound().build(); } } @DeleteMapping("/{id}") public ResponseEntity<Void> deleteEmployee(@PathVariable Long id) { Optional<Employee> employee = employeeService.getEmployeeById(id); if (employee.isPresent()) { employeeService.deleteEmployee(id); return ResponseEntity.noContent().build(); } else { return ResponseEntity.notFound().build(); } } }
Step 7: Running the Application
- Run the Application:
- Open the
SpringBootMysqlCrudApplication
class in thesrc/main/java/com/example/springbootmysqlcrud
directory. - Click the green
Run
button in your IDE or use the terminal to run the application:sh ./mvnw spring-boot:run
- Open the
- Verify the Application:
- Open your web browser or a tool like Postman and navigate to
http://localhost:8080/api/employees
.
- Open your web browser or a tool like Postman and navigate to
You can now perform CRUD operations on the Employee
entity using the following endpoints:
- GET
/api/employees
: Get all employees - GET
/api/employees/{id}
: Get employee by ID - POST
/api/employees
: Create a new employee - PUT
/api/employees/{id}
: Update an existing employee - DELETE
/api/employees/{id}
: Delete an employee
Conclusion
In this tutorial, we have walked through the process of creating a Spring Boot CRUD application with MySQL. We configured the project, set up MySQL, created the necessary entities, repositories, services, and controllers, and tested the CRUD operations. This setup provides a solid foundation for developing more complex Spring Boot applications with MySQL.
Comments
Post a Comment