The Wayback Machine - https://web.archive.org/web/20240930184217/https://www.geeksforgeeks.org/spring-repository-annotation-with-example/
Open In App

Spring @Repository Annotation with Example

Last Updated : 03 Dec, 2021
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

Spring is one of the most popular Java EE frameworks. It is an open-source lightweight framework that allows Java EE 7 developers to build simple, reliable, and scalable enterprise applications. This framework mainly focuses on providing various ways to help you manage your business objects. It made the development of Web applications much easier than compared to classic Java frameworks and application programming interfaces (APIs), such as Java database connectivity (JDBC), JavaServer Pages(JSP), and Java Servlet. This framework uses various new techniques such as Aspect-Oriented Programming (AOP), Plain Old Java Object (POJO), and dependency injection (DI), to develop enterprise applications. Now talking about Spring Annotation

Spring Annotations are a form of metadata that provides data about a program. Annotations are used to provide supplemental information about a program. It does not have a direct effect on the operation of the code they annotate. It does not change the action of the compiled program. 

There are many annotations are available in Spring Framework. Some of the Spring Framework Annotations are listed below as follows where here we are going to discuss one of the most important annotations that is @Repository Annotation

  • @Required
  • @Autowired
  • @Configuration
  • @ComponentScan
  • @Bean
  • @Component
  • @Controller
  • @Service
  • @Repository, etc.

@Repository Annotation

@Repository Annotation is a specialization of @Component annotation which is used to indicate that the class provides the mechanism for storage, retrieval, update, delete and search operation on objects. Though it is a specialization of @Component annotation, so Spring Repository classes are autodetected by spring framework through classpath scanning. This annotation is a general-purpose stereotype annotation which very close to the DAO pattern where DAO classes are responsible for providing CRUD operations on database tables. 

Example

Step 1: Create a Simple Spring Boot Project

Refer to this article Create and Setup Spring Boot Project in Eclipse IDE and create a simple spring boot project. 

Step 2: Add the spring-context dependency in your pom.xml file. Go to the pom.xml file inside your project and add the following spring-context dependency.

XML




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


Step 3: In your project create two packages and name the package as “entity” and “repository”. In the entity, package creates a class name it as Student. In the repository, the package creates a Generic Interface named as DemoRepository and a class name it as StudentRepository. This is going to be our final project structure.

Step 4: Create 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. 

Java




package com.example.demo.entity;
  
public class Student {
  
    private Long id;
    private String name;
    private int age;
  
    public Student(Long id, String name, int age) {
        this.id = id;
        this.name = name;
        this.age = age;
    }
  
    public Long getId() {
        return id;
    }
  
    public void setId(Long id) {
        this.id = id;
    }
  
    public String getName() {
        return name;
    }
  
    public void setName(String name) {
        this.name = name;
    }
  
    public int getAge() {
        return age;
    }
  
    public void setAge(int age) {
        this.age = age;
    }
  
    @Override
    public String toString() {
        return "Student{" +
                "id=" + id +
                ", name='" + name + '\'' +
                ", age=" + age +
                '}';
    }
}


Step 5: Before implementing the Repository class we have created a generic DemoRepository interface to provide the contract for our repository class to implement. Below is the code for the DemoRepository.java file.

Java




// Java Program to illustrate DemoRepository File
  
package com.example.demo.repository;
  
public interface DemoRepository<T> {
  
    // Save method
    public void save(T t);
  
    // Find a student by its id
    public T findStudentById(Long id);
  
}


Step 6: Now let’s look at our StudentRepository class implementation. 

Java




// Java Program to illustrate StudentRepository File
  
package com.example.demo.repository;
  
import com.example.demo.entity.Student;
import org.springframework.stereotype.Repository;
  
import java.util.HashMap;
import java.util.Map;
  
@Repository
public class StudentRepository implements DemoRepository<Student> {
  
    // Using an in-memory Map
    // to store the object data
    private Map<Long, Student> repository;
  
    public StudentRepository() {
        this.repository = new HashMap<>();
    }
  
    // Implementation for save method
    @Override
    public void save(Student student) {
        repository.put(student.getId(), student);
    }
  
    // Implementation for findStudentById method
    @Override
    public Student findStudentById(Long id) {
        return repository.get(id);
    }
}


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.

Note: 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. 

Step 7: Spring Repository Test

So now our Spring Repository is ready, let’s test it out. Go to the DemoApplication.java file and refer to the below code. 

Java




package com.example.demo;
  
import com.example.demo.entity.Student;
import com.example.demo.repository.StudentRepository;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
  
@SpringBootApplication
public class DemoApplication {
  
    public static void main(String[] args) {
          
        AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext();
        context.scan("com.example.demo");
        context.refresh();
  
        StudentRepository repository = context.getBean(StudentRepository.class);
  
        // testing the store method
        repository.save(new Student(1L, "Anshul", 25));
        repository.save(new Student(2L, "Mayank", 23));
  
        // testing the retrieve method
        Student student = repository.findStudentById(1L);
        System.out.println(student);
  
        // close the spring context
        context.close();
    }
  
}


Output: Lastly, run your application and you should get the following output as shown below as follows:



Previous Article
Next Article

Similar Reads

Spring Boot - Difference Between @Service Annotation and @Repository Annotation
Spring Annotations are a form of metadata that provides data about a program. Annotations are used to provide supplemental information about a program. It does not have a direct effect on the operation of the code they annotate. It does not change the action of the compiled program. @Service Annotation In an application, the business logic resides
7 min read
Spring @Controller Annotation with Example
Spring is one of the most popular Java EE frameworks. It is an open-source lightweight framework that allows Java EE 7 developers to build simple, reliable, and scalable enterprise applications. This framework mainly focuses on providing various ways to help you manage your business objects. It made the development of Web applications much easier t
4 min read
Spring - @PostConstruct and @PreDestroy Annotation with Example
Spring is one of the most popular Java EE frameworks. It is an open-source lightweight framework that allows Java EE 7 developers to build simple, reliable, and scalable enterprise applications. This framework mainly focuses on providing various ways to help you manage your business objects. It made the development of Web applications much easier t
13 min read
Spring @Service Annotation with Example
Spring is one of the most popular Java EE frameworks. It is an open-source lightweight framework that allows Java EE 7 developers to build simple, reliable, and scalable enterprise applications. This framework mainly focuses on providing various ways to help you manage your business objects. It made the development of Web applications much easier t
4 min read
Spring Data JPA - Attributes of @Column Annotation with Example
Spring Boot is built on the top of the spring and contains all the features of spring. Spring also provides JPA and hibernate to increase the data manipulation efficiency between the spring application and the database. In very simple terms we can say JPA (Java persistence API) is like an interface and the hibernate is the implementation of the met
3 min read
Spring @ResponseBody Annotation with Example
Spring Annotations allow us to configure dependencies and implement dependency injection through java programs. Those are used to provide supplemental information about a program. It does not have a direct effect on the operation of the code they annotate. It does not change the action of the compiled program. The @ResponseBody annotation tells a c
5 min read
Spring @ComponentScan Annotation with Example
Spring is one of the most popular Java EE frameworks. It is an open-source lightweight framework that allows Java EE 7 developers to build simple, reliable, and scalable enterprise applications. This framework mainly focuses on providing various ways to help you manage your business objects. It made the development of Web applications much easier t
4 min read
Spring @Bean Annotation with Example
One of the most important annotations in spring is the @Bean annotation which is applied on a method to specify that it returns a bean to be managed by Spring context. Spring Bean annotation is usually declared in Configuration classes methods. This annotation is also a part of the spring core framework. So let's understand @Bean Annotation with an
8 min read
Spring @Configuration Annotation with Example
One of the most important annotations in spring is @Configuration annotation which indicates that the class has @Bean definition methods. So Spring container can process the class and generate Spring Beans to be used in the application. This annotation is part of the spring core framework. So let's understand @Configuration Annotation with an examp
4 min read
Spring @RequestMapping Annotation with Example
One of the most important annotations in spring is the @RequestMapping Annotation which is used to map HTTP requests to handler methods of MVC and REST controllers. In Spring MVC applications, the DispatcherServlet (Front Controller) is responsible for routing incoming HTTP requests to handler methods of controllers. When configuring Spring MVC, yo
6 min read
Spring @Value Annotation with Example
One of the most important annotations in spring is @Value annotation which is used to assign default values to variables and method arguments. We can read spring environment variables as well as system variables using @Value annotation. It also supports Spring Expression Language (SpEL). It is generally used for injecting values into configuration
6 min read
Spring Data JPA @Query Annotation with Example
Spring Data JPA or JPA stands for Java Persistence API, so before looking into that, we must know about ORM (Object Relation Mapping). So Object relation mapping is simply the process of persisting any Java object directly into a database table. @Query Annotation is used for defining custom queries in Spring Data JPA. When you are unable to use the
7 min read
Spring @Component Annotation with Example
Spring is one of the most popular Java EE frameworks. It is an open-source lightweight framework that allows Java EE 7 developers to build simple, reliable, and scalable enterprise applications. This framework mainly focuses on providing various ways to help you manage your business objects. It made the development of Web applications much easier c
4 min read
Spring Boot - @LoadBalanced Annotation with Example
The @LoadBalanced annotation creates an instance of created RestTemplate load-balanced. There is no code you need to write to make the RestTemplate load-balance HTTP request it sends to an internal microservice. The RestTemplate bean will be intercepted and auto-configured by Spring Cloud. In brief, we need to use the @LoadBalanced Annotation in ou
11 min read
Spring MVC @SessionAttributes Annotation with Example
In the ever-evolving world of web development, a constant challenge is to seamlessly manage data between requests. Enter Spring MVC's @SessionAttributes annotation, a powerful solution that elegantly manages the session attributes of a Spring application. This markup becomes a lifesaver when certain information must persist throughout the interacti
3 min read
Spring MVC @ModelAttribute Annotation with Example
In Spring MVC, the @ModelAttribute annotation binds a method parameter or method return value to a named model attribute and then exposes it to a web view. It refers to the property of the Model object. For example, if we have a form with a form backing object that is called "Student" then we can have Spring MVC supply this object to a Controller m
8 min read
Spring @Required Annotation with Example
Spring Annotations allow us to configure dependencies and implement dependency injection through java programs. Those are a form of metadata that provides data about a program. The @Required annotation in spring is a method-level annotation used in the setter method of a bean property and therefore making the setter-injection compulsory. This annot
6 min read
Spring @Qualifier Annotation with Example
Spring is one of the most popular Java EE frameworks. It is an open-source lightweight framework that allows Java EE 7 developers to build simple, reliable, and scalable enterprise applications. This framework mainly focuses on providing various ways to help you manage your business objects. It made the development of Web applications much easier t
5 min read
Difference Between @Component, @Repository, @Service, and @Controller Annotations in Spring
Spring Annotations are a form of metadata that provides data about a program. Annotations are used to provide supplemental information about a program. It does not have a direct effect on the operation of the code they annotate. It does not change the action of the compiled program. Here, we are going to discuss the difference between the 4 most im
4 min read
Spring @Autowired Annotation
The @Autowired annotation marks a Constructor, Setter method, Properties and Config() method as to be autowired that is 'injecting beans'(Objects) at runtime by Spring Dependency Injection mechanism which is clearly depicted from the image below as shown: Enabling @Autowired annotation Spring beans can be declared either by Java configuration or XM
3 min read
Spring Data JPA - @Table Annotation
Spring Boot is built on the top of the spring and contains all the features of spring. And is becoming a favorite of developers these days because of its rapid production-ready environment which enables the developers to directly focus on the logic instead of struggling with the configuration and setup. Spring Boot is a microservice-based framework
3 min read
Spring Data JPA - @Id Annotation
Spring Boot is built on the top of the spring and contains all the features of spring. Spring also provides JPA and hibernate to increase the data manipulation efficiency between the spring application and the database. In very simple terms we can say JPA (Java persistence API) is like an interface and the hibernate is the implementation of the met
3 min read
Spring Data JPA - @Column Annotation
Spring Boot is built on the top of the spring and contains all the features of spring. And is becoming a favorite of developers these days because of its rapid production-ready environment which enables the developers to directly focus on the logic instead of struggling with the configuration and setup. Spring Boot is a microservice-based framework
2 min read
Spring - Required Annotation
Consider a scenario where a developer wants to make some of the fields as mandatory fields. using the Spring framework, a developer can use the @Required annotation to those fields by pushing the responsibility for such checking onto the container. So container must check whether those fields are being set or not. The Spring Framework supports a nu
7 min read
Spring - MVC RequestParam Annotation
@RequestParam annotation enables spring to extract input data that may be passed as a query, form data, or any arbitrary custom data. Here, we will see how we can use @RequestParam when building RESTful APIs for a web-based application. Context of the Application: Let us suppose we are implementing a sample feature for the 'Geeksforgeeks' web appli
5 min read
Spring AOP - AspectJ Annotation
AOP i.e Aspect-Oriented Programming complements OOP by enabling modularity of cross-cutting concerns. @AspectJ is mainly used for declaring aspects as regular Java classes annotated with annotations. Spring AspectJ AOP implementation has many annotations. They are explained below: @Aspect: It declares the class as an aspect.@Pointcut: It declares t
4 min read
Difference Between @Controller and @RestController Annotation in Spring
Spring Annotations are a form of metadata that provides data about a program. Annotations are used to provide supplemental information about a program. It does not have a direct effect on the operation of the code they annotate. It does not change the action of the compiled program. @Controller Annotation: Spring @Controller annotation is also a sp
3 min read
Difference Between @Controller and @Service Annotation in Spring
Spring Annotations are a form of metadata that provides data about a program. Annotations are used to provide supplemental information about a program. It does not have a direct effect on the operation of the code they annotate. It does not change the action of the compiled program. Spring @Controller AnnotationSpring @Controller annotation is a sp
5 min read
How to Capture Data using @RequestParam Annotation in Spring?
@RequestParam annotation enables spring to capture input data that may be passed as a query, form data, or any arbitrary custom data. It is used to bind a web request parameter to a method parameter. Here we are going to understand these two above lines and we will see how can we capture data using this annotation. Let's create a simple MVC applica
7 min read
Java Spring - Using @Scope Annotation to Set a POJO's Scope
In the Spring framework, when we declare a POJO instance, what we are actually creating is a template for bean definition. It means, just like a class, we can have many object instances created from a single template. When a bean definition is created, we can control not only the various dependencies and configuration values that are to be plugged
6 min read
Article Tags :
Practice Tags :