Effortless CRUD Operations with Spring Boot and MySQL: A Step-by-Step Guide

Jun 4, 2024

Follow us on


Discover how to perform CRUD operations seamlessly using Spring Boot and MySQL. Our comprehensive guide walks you through every step, from setting up your environment to mastering database interactions.

CRUD OPERATION: SPRING BOOT, MYSQL, HIBERNATE, POSTMAN

Effortless CRUD Operations with Spring Boot and MySQL: A Step-by-Step Guide


šŸ‘‰ FOLLOW THESE STEPS


Step 1: pom.xml

    <?xml version="1.0" encoding="UTF-8"?>
    <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
        <modelVersion>4.0.0</modelVersion>
        <parent>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-parent</artifactId>
            <version>2.7.1</version>
            <relativePath/> <!-- lookup parent from repository -->
        </parent>
        <groupId>com.heycolleagues</groupId>
        <artifactId>CRUD-OPERATION</artifactId>
        <version>0.0.1-SNAPSHOT</version>
        <name>CRUD-OPERATION</name>
        <description>CRUD OPERATION BY HEY COLLEAGUES</description>
        <properties>
            <java.version>17</java.version>
        </properties>
        <dependencies>
            <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>mysql</groupId>
                <artifactId>mysql-connector-java</artifactId>
                <scope>runtime</scope>
            </dependency>
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-test</artifactId>
                <scope>test</scope>
            </dependency>
        </dependencies>
    
        <build>
            <plugins>
                <plugin>
                    <groupId>org.springframework.boot</groupId>
                    <artifactId>spring-boot-maven-plugin</artifactId>
                </plugin>
            </plugins>
        </build>
    
    </project>
    

Step 2: application.properties

    # MySQL connection
    server.port=9091
    spring.datasource.url=jdbc:mysql://localhost:3306/projectcrud
    spring.datasource.username=root
    spring.datasource.password=root
    
    # hibernate Configuration
    spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.MySQL8Dialect
    spring.jpa.hibernate.ddl-auto=update
    spring.jpa.show-sql=true
    spring.jpa.properties.hibernate.format_sql=true


Step 3: class- CrudOperationApplication.java

    package com.heycolleagues;

    import org.springframework.boot.SpringApplication;
    import org.springframework.boot.autoconfigure.SpringBootApplication;
    
    @SpringBootApplication
    public class CrudOperationApplication {
    
        public static void main(String[] args) {
            SpringApplication.run(CrudOperationApplication.class, args);
        }
    
    }
    


Step 4: class- Employee.java

               

    package com.heycolleagues.model;

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

@Entity
public class Employee {
	
	@Id
	@GeneratedValue(strategy = GenerationType.AUTO)
	private Long employeeId;
	
	private String username;
	private String password;
	public Employee(Long employeeId, String username, String password) {
		super();
		this.employeeId = employeeId;
		this.username = username;
		this.password = password;
	}
	public Long getEmployeeId() {
		return employeeId;
	}
	public void setEmployeeId(Long employeeId) {
		this.employeeId = employeeId;
	}
	public String getUsername() {
		return username;
	}
	public void setUsername(String username) {
		this.username = username;
	}
	public String getPassword() {
		return password;
	}
	public void setPassword(String password) {
		this.password = password;
	}
	public Employee() {
		super();
		// TODO Auto-generated constructor stub
	}
	
	

}



Step 5: interface-EmployeeRepository.java

    package com.heycolleagues.repository;

    import org.springframework.data.jpa.repository.JpaRepository;
    import org.springframework.stereotype.Repository;
    
    import com.heycolleagues.model.Employee;
    
    @Repository
    public interface EmployeeRepository extends JpaRepository<Employee, Long>{
        
        public Employee findByUsername(String username);
    
    }
    


Step 6: interface-EmployeeService.java

               

    package com.heycolleagues.service;

import java.util.List;

import com.heycolleagues.model.Employee;


public interface EmployeeService {
	
	public Employee createEmployee(Employee employee);
	public Employee updateEmployee(String username, Employee employee) throws Exception;
	public Employee getEmployeeByUsername(String username);
	public List<Employee> getAllEmployee();
	public void deleteEmployeeById(Long employeeId);

}



Step 7: class-EmployeeServiceImplement.java

               

    package com.heycolleagues.serviceImplement;

import java.util.List;

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

import com.heycolleagues.model.Employee;
import com.heycolleagues.repository.EmployeeRepository;
import com.heycolleagues.service.EmployeeService;

@Service
public class EmployeeServiceImplement implements EmployeeService{
	
	@Autowired
	private EmployeeRepository employeeRepository;

	@Override
	public Employee createEmployee(Employee employee) {
		Employee local = employeeRepository.findByUsername(employee.getUsername());
		if (local == null) {
			System.out.println("Username already taken, \n Try with other username");
		}else {
			local = this.employeeRepository.save(employee);
		}
		return this.employeeRepository.save(employee);
	}

	@Override
	public Employee updateEmployee(String username ,Employee employee) throws Exception {
		Employee local = employeeRepository.findByUsername(username);
		if (local != null) {
			Employee local1 = employeeRepository.findByUsername(employee.getUsername());
			if (local1 != null) {
				throw new Exception("Try with another username for signup \n Thank You!!");
			}else {
				local.setUsername(employee.getUsername());
				local.setPassword(employee.getPassword());
			}
			
			
		}else {
			System.out.println("Please record is founded in our database");
		}
		return this.employeeRepository.save(local);
	}

	@Override
	public Employee getEmployeeByUsername(String username) {
		return this.employeeRepository.findByUsername(username);
	}

	@Override
	public List<Employee> getAllEmployee() {
		return this.employeeRepository.findAll();
	}

	@Override
	public void deleteEmployeeById(Long employeeId) {
		this.employeeRepository.deleteById(employeeId);
		
	}

}



Step 8: class- EmployeeController.class

               


    package com.heycolleagues.controller;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.heycolleagues.model.Employee;
import com.heycolleagues.serviceImplement.EmployeeServiceImplement;

@RestController
@RequestMapping("/api/v1")
public class EmployeeController {
	
	@Autowired
	private EmployeeServiceImplement serviceImplement;
	
	@PostMapping("/create")
	public ResponseEntity<Employee> createEmployee(@RequestBody Employee employee){
		return ResponseEntity.ok(this.serviceImplement.createEmployee(employee));
	}
	
	@PutMapping("/update/{username}")
	public ResponseEntity<Employee> updateEmployee
	(@PathVariable("username") String username ,@RequestBody Employee employee)
	throws Exception
	{
		return ResponseEntity.ok(this.serviceImplement.updateEmployee(username, employee));
	}
	
	@GetMapping("/get/{username}")
	public Employee getEmployeeByUsername(@PathVariable("username") String username) {
		return this.serviceImplement.getEmployeeByUsername(username);
	}

	@GetMapping("/getAllEmployees")
	public List<Employee> getAllEmployee(){
		return this.serviceImplement.getAllEmployee();
	}
	
	@DeleteMapping("/delete/{employeeId}")
	public void deleteEmployeeById(@PathVariable("employeeId") Long id) {
		this.serviceImplement.deleteEmployeeById(id);
	}
}





Ā© 2025 Hey Colleagues. All rights reserved.