Use Of CrudRepository in Spring Boot

Khushi Vashishtha
CodeX
Published in
3 min readSep 14, 2024

--

The CrudRepository interface is a foundational component in Spring Data JPA, providing a set of basic CRUD (Create, Read, Update, Delete) operations for interacting with entities in a JPA-managed repository. It simplifies database interactions, allowing you to focus on business logic rather than writing raw SQL queries.

In Simple words Spring JDBC application discussed above, the Data Object (DAO) implementation class must include the logic for all CRUD operations. These CRUD operations are standard across all Spring Boot applications, and to streamline this, Spring Boot offers predefined methods for all CRUD actions through the CrudRepository interface.

By simply extending the CrudRepository interface in the Repository or DAO interface, all CRUD methods become readily available to the DAO class, eliminating the need for explicit implementation of these operations.

The CrudRepository interface provides the following methods for managing persistence:

  • save()
  • update()
  • delete()
  • find()
  • findById()

To utilize CrudRepository in Spring Boot applications, follow these steps:

  1. Set up a Spring Boot project with these dependencies:
  • Web
  • Spring Data JDBC
  • MySQL Connector

2. Create a table in the database with an auto_increment feature for the primary key. This should be done on a MySQL database server.

create table emp1 (
ENO int(3) primary key auto_increment,
ENAME char(10),
ESAL float(5),
EADDR char(10)
);

3. Develop a bean class or model class; it must be annotated with @Table, and the id field should have @Id.

4. Create a repository interface by extending CrudRepository.

5. Formulate a service class, annotated with @Service. Each method within the service class should be marked with @Transactional.

6. Construct a controller class with @Controller.

7. Create a runner class to test the application.

Project Name: [SpringBootappCRUDRepository]

application.properties

application.properties

[Employee.java]

Employee.java inside beans package

[EmployeeRepository.java]

EmployeeRepository.java

[EmployeeService.java]

EmployeeService.java Interface inside service package

[EmployeeServiceImpl.java]

EmployeeServiceImpl.java inside service package

[EmployeeController.java]

EmployeeController.java inside controller package

[EmployeeRunner.java]

EmployeeRunner.java inside runner package

[SpringbootJdbc24Application.java]

SpringbootJdbc24Application.java

--

--

Khushi Vashishtha
CodeX

CS student | Java Developer | Tech Blogger @ Medium | Sharing Java insights, tutorials, and tips.