CRUD Operation in Spring Boot
Posted By : Bhupendra Singh Yadav | 29-Jun-2022
What is CRUD operation in Spring Boot?
In the CRUD operation, there are four basic operations like CREATE, READ/RETRIEVE, UPDATE and DELETE with the help of these CRUD operations we can persist the data in the database.
It is data-oriented and the standardized use of HTTP methods. HTTP has a few essential methods which work as CRUD operations.
Standard CRUD operations are as follows:-
POST:- Creates a new record
GET:- Retrieve/Read all the records
PUT:- Updates an existing record
DELETE:- Deletes a record
CRUD operations name suggests as-
CREATE- Create an operation used to create the new record into the database.
RETRIEVE- Read/Retrieve operation used to retrieve the data from the database.
UPDATE- The update operation is used to update/Edit the record present in the database.
DELETE - Delete operation used to delete records from the database.
Here, We are performing some basic CRUD Operations by creating a Spring Boot Application and using the MySQL Database.
Implementation
Create and set up a spring boot project.
We use the following IDEs (Integrated Development Environment)to create a Spring Boot project.
1- Intellij
2- Eclipse
3- STS(Spring Tool Suite)
Project Setup:-
The simplest way to create a new spring boot application is to use the spring initializer.
i) Open spring initializer in your web browser.
ii) Choose the Maven project.
iii) Choose Java as the language.
iv) Leave the default selected Spring Boot version.
v) Select Java 8 as the Java Version.
vi) Add Spring Web, Spring Data JPA, and MYSQL Driver in the dependencies section.
vii) Click on the generate button to download the project as a zip file.
viii) Extract the zip file and open the project in your favorite IDE.
# Configuration for MySQL Database
spring.datasource.url=jdbc:mysql://localhost:3306/employee
server.port=8080
spring.datasource.username=root
spring.datasource.password=root@123
spring.datasource.Driver-class-name=com.mysql.cj.jdbc.Driver
spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.MySQL8Dialect
spring.jpa.properties.hibernate.ddl-auto=create
spring.jpa.hibernate.ddl-auto=create
spring.jpa.show-sql=true
JPA Repository
JPARepository is a JPA (Java Persistence API) specific repository. It is defined in Spring Data JPA and it extends both repository CrudRepository and PagingAndSortingRepository. These repositories contain API for basic CRUD operations and also API for pagination and sorting.
Syntax-
@Repository
public interface EmployeeRepository extends JPARepository<T, ID> {
}
Where
T:- It is generally the Entity/Model name
ID:- It is the type of the id of the entity that repository manages.
Create a Java class with the name Employee with the fields as shown below.
@Entity
@Table(name = "employee")
public class Employee{
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private long id;
@Column(name = "firstName")
private String firstName;
@Column(name = "middleName")
private String middleName;
@Column(name = "lastName")
private String lastName;
@Column(name = "address")
private String address;
public Employee(){
}
public Employee(long id, String firstName, String middleName, String lastName, String address) {
this.id = id;
this.firstName = firstName;
this.middleName = middleName;
this.lastName = lastName;
this.address = address;
}
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 getMiddleName() {
return middleName;
}
public void setMiddleName(String middleName) {
this.middleName = middleName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
Creating the repository interface
@Repository
public interface EmployeeRepository extends JPARepository<Employee, Long> {
}
Creating the Employee service
@Service
public class EmployeeService {
@Autowired
EmployeeRepository repository;
public List<Employee> getAllEmployee() {
return (List<Employee>) repository.findAll();
}
public String save(Employee employee) {
return repository.save(employee);
}
public void delete(Long id) {
repository.deleteById(id);
}
public Employee getId(Long id) {
return repository.findById(id).get();
}
public Employee update(Long id,Employee employee){
Employee employee1 = repository.findById(id).get();
employee1.setFirstName(employee.getFirstName());
employee1.setMiddleName(employee.getMiddleName());
employee1.setLastName(employee.getLastName());
employee1.setAddress(employee.getAddress());
return repository.save(employee1);
}
}
Creating the Rest API controller
In the controller's package, we created above, create a Java class with the name EmployeeController.
@RestController
public class EmployeeController {
@Autowired
EmployeeService service;
// Read operation
@GetMapping("/getAll")
public List<Employee> getAllEmployee() {
return service.getAllEmployee();
}
// Save operation
@PostMapping("/create")
public String create(@RequestBody Employee employee) {
service.save(employee);
return "Data Successfully Created";
}
// Delete operation
@DeleteMapping("/delete/{id}")
public String delete(@PathVariable Long id) {
service.delete(id);
return "Data Delete Succesfully";
}
// Read operation by ID
@GetMapping("/getId/{id}")
public Employee getId(@PathVariable Long id) {
Employee employee = service.getId(id);
return employee;
}
// Update operation
@PutMapping("/update/{id}")
public Employee update(@PathVariable Long id, @RequestBody Employee employee) {
service.update(id, employee);
return "Update date Succesfully";
}
}
Cookies are important to the proper functioning of a site. To improve your experience, we use cookies to remember log-in details and provide secure log-in, collect statistics to optimize site functionality, and deliver content tailored to your interests. Click Agree and Proceed to accept cookies and go directly to the site or click on View Cookie Settings to see detailed descriptions of the types of cookies and choose whether to accept certain cookies while on the site.
About Author
Bhupendra Singh Yadav
He is energetic and enthusiastic about his work and also consistent with attentive to details. He has skills like Java ,C Language and DBMS. And currently he is working on Spring Boot APIs.