Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Implementing CrudRepository in Spring. What's the best design I should follow?

I have the User Repository extend from the CrudRepository as below

public interface UserRepository extends CrudRepository<User, Long>, DatatablesCriteriasRepository<User> 

DatatablesCriteriasRepository has a function which need to be implmented separately for different repositories.

So I created the repository implementation class like this. In the impl package.

public class UserRepositoryImpl implements DatatablesCriteriasRepository<User> 

Please note this is to implement the functions in DatatablesCriteriasRepository only. I dont want to override the default functionalities presented in CrudRepository by the framework.

But If I do something like this, it will suit more in the code design, as UserRepositoryImpl actually implements UserRepository as the name suggests.

public class UserRepositoryImpl implements UserRepository 

But again this will force me to extend all the functions in the UserRepository interface. How can I solve this issue by the way in a good code design?

Can the UserRepositoryImpl has this name while it implements DatatablesCriteriasRepository?

like image 835
Faraj Farook Avatar asked Apr 06 '15 08:04

Faraj Farook


People also ask

Which is best JpaRepository or CrudRepository?

Crud Repository doesn't provide methods for implementing pagination and sorting. JpaRepository ties your repositories to the JPA persistence technology so it should be avoided. We should use CrudRepository or PagingAndSortingRepository depending on whether you need sorting and paging or not.

How is CrudRepository implemented?

CrudRepository is a Spring data interface and to use it we need to create our interface by extending CrudRepository for a specific type. Spring provides CrudRepository implementation class automatically at runtime. It contains methods such as save , findById , delete , count etc.


1 Answers

Spring's repositories custom implementations documentation provides the way to implement this as @JBNizet pointed it to me.

Extract from the documentation is as follows.

Interface for custom repository functionality

interface UserRepositoryCustom {
  public void someCustomMethod(User user);
}

Implementation of custom repository functionality

class UserRepositoryImpl implements UserRepositoryCustom {

  public void someCustomMethod(User user) {
    // Your custom implementation
  }
}

Changes to the your basic repository interface

interface UserRepository extends CrudRepository<User, Long>, UserRepositoryCustom {

  // Declare query methods here
}
like image 153
Faraj Farook Avatar answered Oct 16 '22 07:10

Faraj Farook