Table of contents
1.
Introduction
2.
What is @Repository in Spring Boot?
2.1.
Spring Repository Example
3.
Important Spring Boot Annotation
4.
Implementation of @repository annotation
4.1.
Employee.java
4.2.
GenRepository.java
4.3.
EmployeeDao.java
4.4.
App.java
5.
Features of Repository Annotation
6.
Frequently Asked Questions
6.1.
What is repository annotation?
6.2.
Is @repository annotation necessary?
6.3.
What is @repository in Java?
6.4.
What is the purpose of repository in Spring boot?
6.5.
Is @repository mandatory in Spring Boot?
7.
Conclusion
Last Updated: Feb 6, 2025
Medium

Spring @Repository Annotation

Author Gunjan Batra
0 upvote
Career growth poll
Do you think IIT Guwahati certified course can help you in your career?

Introduction

In Spring Framework, the @Repository annotation plays a crucial role in defining data access objects (DAOs). It is a specialized component of the Spring stereotype annotations, primarily used to indicate that a class interacts with a database. By marking a class with @Repository, Spring enables automatic exception translation, converting database-related exceptions into Spring’s DataAccessException, making error handling more manageable.

Repository Annotation

What is @Repository in Spring Boot?

Spring has various annotations, and one such annotation is @component. The specialization of annotation @component is @repository. The @repository annotation is built on the top of the classes that manage the code related to the database. The annotation helps to easily retrieve, update, and delete content in the database. 

Repository Annotation in Spring

 Also, by using the annotation @component, you create beans with lesser codes. Repository annotation helps to find the repository class. The repository class is the class that represents the database. You write this annotation just above the class used for the database. This annotation is similar to the DAO (Direct Access Object) class responsible for CRUD operation.

Spring Repository Example

@Repository
public class CustomerRepositoryImpl implements CustomerRepository {
   @Autowired
   private JdbcTemplate jdbcTemplate;
   @Override
   public List<Customer> getAllCustomers() {
       String sql = "SELECT * FROM customers";
       return jdbcTemplate.query(sql, new BeanPropertyRowMapper<>(Customer.class));
   }
   // other methods for customer repository
}


In this example, the CustomerRepositoryImpl class is annotated with @Repository to indicate that it is a repository component in the Spring application. The class implements the CustomerRepository interface and uses JdbcTemplate to query the database and return a list of Customer objects. The @Autowired annotation is used to inject the JdbcTemplate instance into the class.

Click on the following link to read further : Hackerearth Test Questions and Answers

Important Spring Boot Annotation

  • @Repository – Marks a class as a Data Access Object (DAO) and enables exception translation for database operations.
  • @Entity – Specifies a class as a JPA entity, mapping it to a database table.
  • @Table – Defines the table name associated with a JPA entity.
  • @Id – Marks a field as the primary key of an entity.
  • @GeneratedValue – Specifies the primary key generation strategy.
  • @Column – Defines column-specific properties like name, length, and constraints.
  • @RepositoryRestResource – Exposes Spring Data repositories as RESTful web services.
  • @Query – Used to define custom JPQL or native SQL queries for repository methods.
  • @Transactional – Ensures transactional integrity for database operations within a repository.

Implementation of @repository annotation

It is important to understand the annotation through implementation. 

The class that will give the information about the data will be annotated with the annotation @repository. 

To use the annotation, we require context dependency in our pom.xml file.

Below is the dependency you must add to your pom.xml file:

<dependency>
    <groupId>org.springframework</groupId>
      <artifactId>spring-context</artifactId>
      <version>5.3.24</version>
</dependency>


The layout of the application will look like this:

layout of the application

We have created a maven project named Annotations in STS. We have two packages inside the Annotations.

  1. Entity package: Inside this, we have an employee class.
     
  2. Repository package: Inside this, we have one class and one interface, EmployeeDao as a class and an interface GenRepository.
     

When you explore the maven dependency, you can see that the spring-context dependency is added.  

Employee.java

package com.CN.Annotations.entity;

public class Employee {

  private int id;
  private String name;

  public Employee(int id, String name) {
   this.id= id;
   this.name= name; 
 }
  public int getId() {
   return id; 
 }
  public void setId(int id) {
   this.id =id;
 }
  public String getName() {
   return name; 
 }
  public void setName(String name) {
   this.name = name;
 }
 @Override
  public String toString() {
   return id +" ," + name;
 }
  public void printEmployee(int id, String name) {
   System.out.println("Employee id is "+ id +" and name is: " +name);
 }

}

GenRepository.java

This is the generic class. Here T is generic to the object we refer to. We have three methods in this interface. These methods are overridden in the class that implements this interface.

package com.CN.Annotations.Repository;

public interface GenRepository<T> {
 public void save(T t);
 public T findEmployeeById(int id);
 public T deleteEmployee(int id);

}

Also see,  Install Homebrew

EmployeeDao.java

The EmployeeDao class is the repository class. This class helps in retrieving, deleting, and updating the data. This class implements the GenRepository interface and overrides the method of the interface.

package com.CN.Annotations.Repository;
import java.util.HashMap;
import java.util.Map;
import org.springframework.stereotype.Repository;
import com.CN.Annotations.entity.Employee;
@Repository
public class EmployeeDao implements GenRepository<Employee> {
private Map <Integer, Employee> dao;

 public EmployeeDao() {
  this.dao= new HashMap<>();

 }
   @Override
 public void save(Employee employee) {
  dao.put(employee.getId(), employee);
 }

   @Override
 public Employee findEmployeeById(int id) {
  return dao.get(id);
 }
 
   @Override
  public Employee deleteEmployee(int id) {
   Employee emp= dao.get(id);
   this.dao.remove(emp);
   return emp; 
   }

}

App.java

The program begins from app.java file. Through this, we have tried to add the data to the repository class. The dao object we get is through the context object we obtain by AnnotationConfigApplicationContext.

The data is then printed by getting the data from the findEmployeeById method.

package com.CN.Annotations;

import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;

import com.CN.Annotations.Repository.EmployeeDao;
import com.CN.Annotations.entity.Employee;

public class App 
{
    public static void main( String[] args )
    {
     AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext ();
     context.scan("com.CN.Annotations");
     context.refresh();
     EmployeeDao dao= context.getBean(EmployeeDao.class);
     dao.save(new Employee(1,"Aman"));
     dao.save(new Employee(19,"Manan"));
     dao.save(new Employee(16,"Shubham"));
     dao.save(new Employee(14,"Ayush"));
     dao.save(new Employee(6,"Payal"));
     Employee emp = dao.findEmployeeById(19);
     Employee emp1 = dao.findEmployeeById(16);
     System.out.println(emp);
     System.out.println(emp1);
     Employee empp = dao.deleteEmployee(14);
     System.out.println(empp);
    }
}


Output:

Below is the output when we run the application as a java application. 

Output

Features of Repository Annotation

Repository annotation lets you showcase the class that provides connectivity with the database. You can modify the data through the @repository annotation class. Different features of Repository Annotation are as follows:

  1. Retrieve data from the table
     
  2. Save data to the table
     
  3. Update data in the table
     
  4. Delete data from the data

Frequently Asked Questions

What is repository annotation?

The @Repository annotation in Spring is used to indicate that a particular class is a repository component in a Spring application. It is used to enable automatic exception translation and provides access to data persistence and retrieval mechanisms.

Is @repository annotation necessary?

No, the @Repository annotation is not strictly necessary for a Spring application to function, but it is considered a good practice to use it to indicate that a particular class is a repository component and to benefit from Spring's automatic exception translation for data access exceptions.

What is @repository in Java?

In Java, "@Repository" is an annotation used to indicate that a class is a repository, which is a component responsible for accessing and manipulating data from a database. It is typically used in conjunction with other annotations, such as "@Autowired" and "@Transactional", to provide additional functionality.

What is the purpose of repository in Spring boot?

In Spring Boot, a repository is used to manage data persistence and retrieval in a database. It provides an abstraction layer over the database and simplifies the process of interacting with it, allowing developers to focus on business logic rather than database operations.

Is @repository mandatory in Spring Boot?

No, @Repository is not mandatory in Spring Boot. Spring Data JPA automatically detects repository interfaces extending JpaRepository, but @Repository enables exception translation for better error handling.

Conclusion

In this blog, we have discussed repository annotations. We looked at the features and implementation of the annotation. We code a spring project using the annotation for better understanding.  

To learn more about Spring, please refer to the blogs given below:

Live masterclass