Tutorial

Spring @Repository Annotation

Published on August 3, 2022
author

Pankaj

Spring @Repository Annotation

Spring @Repository annotation is used to indicate that the class provides the mechanism for storage, retrieval, search, update and delete operation on objects.

Spring @Repository Annotation

Spring Repository annotation is a specialization of @Component annotation, so Spring Repository classes are autodetected by spring framework through classpath scanning. Spring Repository is very close to DAO pattern where DAO classes are responsible for providing CRUD operations on database tables. However, if you are using Spring Data for managing database operations, then you should use Spring Data Repository interface.

Spring Repository Example

Let’s look at a simple example where we will create a Spring Repository class. We will not use database operations, rather we will provide a repository for an Object. Create a maven project in Eclipse or any other IDE you use, then add spring core dependency.

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

Below image shows our final project structure in Eclipse. Spring Repository Example Let’s create the model class for which we will implement a spring repository.

package com.journaldev.spring.model;

public class Employee {

	private int id;
	private String name;
	private String jobTitle;

	public Employee() {
	}

	public Employee(int i, String n, String jt) {
		this.id = i;
		this.name = n;
		this.jobTitle = jt;
	}

	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;
	}

	public String getJobTitle() {
		return jobTitle;
	}

	public void setJobTitle(String jobTitle) {
		this.jobTitle = jobTitle;
	}

	@Override
	public String toString() {
		return id + "," + name + "," + jobTitle;
	}
}

Before we implement Repository class, I have created a generic ObjectRepository interface to provide the contract for our repository class to implement.

package com.journaldev.spring.repository;

public interface ObjectRepository<T> {

	public void store(T t);

	public T retrieve(int id);

	public T search(String name);

	public T delete(int id);
}

I am using Generics here, it’s a powerful technology to provide loosely coupled contract for the applications to implement. Now let’s look at our Repository class implementation.

package com.journaldev.spring.repository;

import java.util.Collection;
import java.util.HashMap;
import java.util.Map;

import org.springframework.stereotype.Repository;

import com.journaldev.spring.model.Employee;

@Repository
public class EmployeeRepository implements ObjectRepository<Employee> {

	private Map<Integer, Employee> repository;

	public EmployeeRepository() {
		this.repository = new HashMap<>();
	}

	@Override
	public void store(Employee emp) {
		repository.put(emp.getId(), emp);
	}

	@Override
	public Employee retrieve(int id) {
		return repository.get(id);
	}

	@Override
	public Employee search(String name) {
		Collection<Employee> emps = repository.values();
		for (Employee emp : emps) {
			if (emp.getName().equalsIgnoreCase(name))
				return emp;
		}
		return null;
	}

	@Override
	public Employee delete(int id) {
		Employee e = repository.get(id);
		this.repository.remove(id);
		return e;
	}

}

Note that I am using an in-memory Map to store the object data, you can use any other mechanisms too.

Spring Repository Test

Our Spring Repository is ready, let’s create a main class and test it out.

package com.journaldev.spring;

import java.sql.SQLException;

import org.springframework.context.annotation.AnnotationConfigApplicationContext;

import com.journaldev.spring.model.Employee;
import com.journaldev.spring.repository.EmployeeRepository;

public class SpringMainClass {

	public static void main(String[] args) throws SQLException {
		AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext();
		context.scan("com.journaldev.spring");
		context.refresh();

		EmployeeRepository repository = context.getBean(EmployeeRepository.class);

		// store
		repository.store(new Employee(1, "Pankaj", "CEO"));
		repository.store(new Employee(2, "Anupam", "Editor"));
		repository.store(new Employee(3, "Meghna", "CFO"));

		// retrieve
		Employee emp = repository.retrieve(1);
		System.out.println(emp);

		// search
		Employee cfo = repository.search("Meghna");
		System.out.println(cfo);

		// delete
		Employee editor = repository.delete(2);
		System.out.println(editor);

		// close the spring context
		context.close();
	}

}

Just run the class as Java Application and you should get following output.

1,Pankaj,CEO
3,Meghna,CFO
2,Anupam,Editor

You can download the example code from our GitHub Repository.

Reference: API Doc

Thanks for learning with the DigitalOcean Community. Check out our offerings for compute, storage, networking, and managed databases.

Learn more about our products

About the authors
Default avatar
Pankaj

author

While we believe that this content benefits our community, we have not yet thoroughly reviewed it. If you have any suggestions for improvements, please let us know by clicking the “report an issue“ button at the bottom of the tutorial.

Still looking for an answer?

Ask a questionSearch for more help

Was this helpful?
 
JournalDev
DigitalOcean Employee
DigitalOcean Employee badge
January 24, 2021

You can take off the annotation @Repository and thing should work. This sample has nothing to do with @Repository. Wasting my 10 min to read your code

- Gordon Ko

    JournalDev
    DigitalOcean Employee
    DigitalOcean Employee badge
    November 26, 2020

    Hey, “Spring @Repository annotation is used to indicate that the class provides the mechanism for storage, …” I don’t really understand if use of @Repository annotation is really needed here. You didn’t use any other annotatations so is indication of a storage really needed for proper work of this example? I have seen in your next tutorial ( https://www.journaldev.com/17034/spring-data-jpa ) that you didn’t use @Repository. Can you explain me that? Thanks in advance

    - Peter

      JournalDev
      DigitalOcean Employee
      DigitalOcean Employee badge
      March 16, 2020

      Exception in thread “main” org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type ‘com.journaldev.repository.EmployeeRepository’ available at org.springframework.beans.factory.support.DefaultListableBeanFactory.getBean(DefaultListableBeanFactory.java:351) at org.springframework.beans.factory.support.DefaultListableBeanFactory.getBean(DefaultListableBeanFactory.java:342) at org.springframework.context.support.AbstractApplicationContext.getBean(AbstractApplicationContext.java:1126) at com.journaldev.SpringMainClass.main(SpringMainClass.java:18)

      - Neelove Basu

        JournalDev
        DigitalOcean Employee
        DigitalOcean Employee badge
        August 13, 2019

        HEY ITS GIVING THIS ERROR: INFO: Pre-instantiating singletons in org.springframework.beans.factory.support.DefaultListableBeanFactory@75412c2f: defining beans [org.springframework.context.annotation.internalConfigurationAnnotationProcessor,org.springframework.context.annotation.internalAutowiredAnnotationProcessor,org.springframework.context.annotation.internalRequiredAnnotationProcessor,org.springframework.context.annotation.internalCommonAnnotationProcessor,org.springframework.context.annotation.ConfigurationClassPostProcessor$ImportAwareBeanPostProcessor#0]; root of factory hierarchy Exception in thread “main” org.springframework.beans.factory.NoSuchBeanDefinitionException: No unique bean of type [com.nucleus.Repository.EmployeeRepo] is defined: expected single bean but found 0: at org.springframework.beans.factory.support.DefaultListableBeanFactory.getBean(DefaultListableBeanFactory.java:271) at org.springframework.context.support.AbstractApplicationContext.getBean(AbstractApplicationContext.java:1101) at com.nucleus.Repository.Main.main(Main.java:15)

        - Aashima

          JournalDev
          DigitalOcean Employee
          DigitalOcean Employee badge
          July 14, 2019

          What happens if I use component instead of repository annotation.

          - Suriya

            JournalDev
            DigitalOcean Employee
            DigitalOcean Employee badge
            February 3, 2019

            not working getting error

            - deepak

              Try DigitalOcean for free

              Click below to sign up and get $200 of credit to try our products over 60 days!

              Sign up

              Join the Tech Talk
              Success! Thank you! Please check your email for further details.

              Please complete your information!

              Become a contributor for community

              Get paid to write technical tutorials and select a tech-focused charity to receive a matching donation.

              DigitalOcean Documentation

              Full documentation for every DigitalOcean product.

              Resources for startups and SMBs

              The Wave has everything you need to know about building a business, from raising funding to marketing your product.

              Get our newsletter

              Stay up to date by signing up for DigitalOcean’s Infrastructure as a Newsletter.

              New accounts only. By submitting your email you agree to our Privacy Policy

              The developer cloud

              Scale up as you grow — whether you're running one virtual machine or ten thousand.

              Get started for free

              Sign up and get $200 in credit for your first 60 days with DigitalOcean.*

              *This promotional offer applies to new accounts only.