Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using repository annotation when implementing JpaRepostiory in Spring

I'm not sure if I understand it correctly so want to clarify. If I want to create a repository for my entity eg.:

public interface BookRepository extends JpaRepository<Book, Id> {}

Should I annotate it with @Repository? According to this question @Repository annotation translates exceptions from SQL to persistence ones but doesn't JpaRepostiory already do that? What's the best practice - to annotate or not?

like image 949
ohwelppp Avatar asked Mar 09 '17 09:03

ohwelppp


People also ask

Does JpaRepository need Repository annotation?

You need to annotate it with @Repository so spring knows it should instantiate that class as a bean. The @Component, @Service and @Repository annotations all serve the same purpose in that regard.

What is the use of @repository annotation in Spring?

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

Can we use @transactional in Repository?

The usage of the @Repository annotation or @Transactional . @Repository is not needed at all as the interface you declare will be backed by a proxy the Spring Data infrastructure creates and activates exception translation for anyway.


1 Answers

While using JpaRepository you don't need to annotate the interface with @Repository

It is just an interface and the concrete implementation is created dynamically as a proxy object by Spring and the JDBC Exceptions are handled there.

You need to use @Repository when you create a Custom DAO, so that spring creates a bean and handles the exception properly.

like image 92
Avinash Avatar answered Sep 28 '22 19:09

Avinash