![]() |
VOOZH | about |
The @Repository annotation is used in the persistence layer of a Spring application to interact with the database. Classes marked with @Repository contain the code required to perform CRUD operations and other database-related tasks. It acts as a bridge between the business layer and the database layer, helping maintain a clean separation of responsibilities within the application.
Let's consider a simple example to understand how to use the @Repository annotation in a Spring Boot application.
Refer to this article Create and Setup Spring Boot Project in Eclipse IDE and create a simple spring boot project.
In your pom.xml file, add the following spring-context dependency.
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>5.3.13</version>
</dependency>
Create two packages: entity and repository. Inside the entity package, create a Student class. In the repository package, create a generic interface named DemoRepository and a class named StudentRepository.
π ImageCreate an entity class for which we will implement a spring repository. Here our entity class is Student. Below is the code for the Student.java file. This is a simple POJO (Plain Old Java Object) class in Java.
Student.java:
Before implementing the Repository class we have created a generic DemoRepository interface to define the contract for our repository class. Below is the code for the DemoRepository.java file.
Now letβs look at the implementation of our StudentRepository class.
In this StudentRepository.java file, you can notice that we have added the @Repository annotation to indicate that the class provides the mechanism for storage, retrieval, update, delete and search operation on objects.
π ImageNote: Here we have used an in-memory Map to store the object data, you can use any other mechanisms too. In the real world, we use Databases to store object data.
Now our Spring Repository is ready, letβs test it out. Go to the DemoApplication.java file and refer to the below code.
Output:
π Image