Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

@Repository not necessary when implementing JpaRepository?

I have a repository class in my spring boot app. First, I annotated it with @Repository and then I implemented JpaRepository. Now I got rid of the annotation and it still works.

I saw that JpaRepository has the @NoRepositoryBean annotation.

How does this work? Or should this not work and there's something weird going on in my application?

like image 824
user3813234 Avatar asked May 19 '17 11:05

user3813234


People also ask

Does JpaRepository need repository Annotation?

No, you don't need to when using Spring Data JPA.

Is @repository Annotation mandatory?

It is indeed not necessary to put the @Repository annotation on interfaces that extend JpaRepository ; Spring recognises the repositories by the fact that they extend one of the predefined Repository interfaces.

Do I need @repository in Spring?

Do I need it or not? No, you don't need to add @Repository explicitly. Spring Data understands that your interface is a repository interface because it extends CrudRepository .

What is @repository Annotation used for?

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


2 Answers

It is indeed not necessary to put the @Repository annotation on interfaces that extend JpaRepository; Spring recognises the repositories by the fact that they extend one of the predefined Repository interfaces.

The purpose of the @NoRepositoryBean annotation is to prevent Spring from treating that specific interface as a repository by itself. The JpaRepository interface has this annotation because it isn't a repository itself, it's meant to be extended by your own repository interfaces, and those are the ones that should be picked up.

Or should this not work and there's something weird going on in my application?

It works as it should and there is nothing weird going on in your application.

like image 83
Jesper Avatar answered Sep 19 '22 14:09

Jesper


It is not mandatory. The reason it will be working is beacause, you would have specified to framework the packages to look for repositories using @EnableJpaRepositories("packagestoscan")

like image 31
pvpkiran Avatar answered Sep 18 '22 14:09

pvpkiran