Spring Boot CRUD
Step 1: Create the Database in MySQL
First, create the database in MySQL.
- Open MySQL Workbench (or any MySQL client).
- Run the following SQL commands to create the database and the table:
CREATE DATABASE berojgar_management;
USE berojgar_management;
1st Query=> create database berojgar_management;
2nd Query => USE berojgar_management;
3rd Query => create table berojgar(berojgar_id INT auto_increment primary key,
berojgar_name varchar(255)) ;
=============================================================================================
Step 2: Create the Spring Boot Project
Java: 17 (or your preferred version)
Go to Spring Initializr:
Visit Spring Initializr.
Configure the Project:
Project: Maven
Language: Java
Spring Boot: Latest stable version
Group: com.example
Artifact: berojgar-management
Name: Berojgar Management
Package name: com.example.berojgarmanagement
Packaging: Jar
Add Dependencies:
- Spring Web: For building web applications.
- Spring Data JPA: For interacting with the database.
- MySQL Driver: To connect to MySQL.
- Spring Boot DevTools: Optional, for development.
Generate and Download the Project.
Extract the downloaded ZIP file and open it in IntelliJ IDEA.
=============================================================================================
Step 3: Configure the Application Properties
In src/main/resources/application.properties
, configure the MySQL database connection:
spring.datasource.url=jdbc:mysql://localhost:3306/berojgar_management
spring.datasource.username=root
spring.datasource.password=mysql
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.jpa.hibernate.ddl-auto=update
spring.jpa.show-sql=true
spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.MySQL8Dialect
server.port=8081
Replace your_username
and your_password
with your MySQL credentials.
=============================================================================================
Step 4: Create the Entity Class
- Create a package named
model
undersrc/main/java/com/example/berojgarmanagement
. - Create a Java class named
Berojgar
in themodel
package:
This is Entity Code
package com.example.berojgar_management.model;
import jakarta.persistence.*;
import lombok.Data;
@Entity
@Data
public class Berojgar {// 1st is create db and table //2nd step entity
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer berojgarId;
private String berojgarName;
}
=============================================================================================
Step 5: Create the Repository Interface
- Create a package named
repository
. - Create a Java interface named
BerojgarRepository
in therepository
package:
This is Repository Code:
package com.example.berojgar_management.repository;
import com.example.berojgar_management.model.*;
import org.springframework.data.jpa.repository.JpaRepository;
public interface BerojgarRepository extends JpaRepository<Berojgar, Integer> {//3rd step
}
=============================================================================================
Step 6: Create the Service Layer
- Create a package named
service
. - Create a Java class named
BerojgarService
in theservice
package:
This is Service Code:
package com.example.berojgar_management.service;
import com.example.berojgar_management.exception.ResourceNotFoundException;
import com.example.berojgar_management.model.Berojgar;
import com.example.berojgar_management.repository.BerojgarRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
import java.util.Map;
import java.util.Optional;
@Service
public class BerojgarService {
@Autowired
private BerojgarRepository berojgarRepository;
public List<Berojgar> getAllBerojgars() {
return berojgarRepository.findAll();
}
public Optional<Berojgar> getBerojgarById(int id) {
return berojgarRepository.findById(id);
}
public Berojgar saveBerojgar(Berojgar berojgar) {
return berojgarRepository.save(berojgar);
}
public void deleteBerojgar(int id) {
berojgarRepository.deleteById(id);
}
}
=============================================================================================
Step 7: Create the Controller Layer
- Create a package named
controller
. - Create a Java class named
BerojgarController
in thecontroller
package:
This is Controller Code:
package com.example.berojgar_management.controller;
import com.example.berojgar_management.model.Berojgar;
import com.example.berojgar_management.service.BerojgarService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import java.util.List;
@RestController
@RequestMapping(“/api/berojgars”)
public class BerojgarController {
@Autowired
private BerojgarService berojgarService;
@GetMapping
public List<Berojgar> getAllBerojgars() {
return berojgarService.getAllBerojgars();
}
@GetMapping(“/{id}”)
public ResponseEntity<Berojgar> getBerojgarById(@PathVariable int id) {
return berojgarService.getBerojgarById(id)
.map(ResponseEntity::ok)
.orElse(ResponseEntity.notFound().build());
}
@PostMapping
public Berojgar createBerojgar(@RequestBody Berojgar berojgar) {
return berojgarService.saveBerojgar(berojgar);
}
@PutMapping(“/{id}”)
public ResponseEntity<Berojgar> updateBerojgar(@PathVariable int id, @RequestBody Berojgar berojgarDetails) {
return berojgarService.getBerojgarById(id)
.map(berojgar -> {
berojgar.setBerojgarName(berojgarDetails.getBerojgarName());
Berojgar updatedBerojgar = berojgarService.saveBerojgar(berojgar);
return ResponseEntity.ok(updatedBerojgar);
}).orElse(ResponseEntity.notFound().build());
}
@DeleteMapping(“/{id}”)
public ResponseEntity<Void> deleteBerojgar(@PathVariable int id) {
return berojgarService.getBerojgarById(id)
.map(berojgar -> {
berojgarService.deleteBerojgar(id);
return ResponseEntity.ok().<Void>build();
}).orElse(ResponseEntity.notFound().build());
}
}
=============================================================================================
NOTE: All Given Code is working You may get error like import or package name class name so create classes and package as shown in in above image if you are not able to run then comment then we will try to help you
Postman URL’s behalf of our code
POST URL => http://localhost:8081/api/berojgars
select post then select Body then raw then JSON
{
“berojgarName“: “Test2 “
}
then click on send
————————————————————————————————————————————————————-
GET URL => http://localhost:8081/api/berojgars/
then click on send
————————————————————————————————————————————————————-
PUT URL => http://localhost:8081/api/berojgars/10
select PUT then select Body then raw then JSON
{
“berojgarName”: “Test2 Update “
}
then click on send
here 10 is id behalf of id we update the 10th number of record
————————————————————————————————————————————————————-
DELETE URL => http://localhost:8081/api/berojgars/10
here 10 is id behalf of id we delete the 10th number of record
=============================================================================================
Leave a Reply