Faraj Farook
Faraj Farook

Reputation: 14885

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?

Upvotes: 10

Views: 18593

Answers (1)

Faraj Farook
Faraj Farook

Reputation: 14885

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
}

Upvotes: 18

Related Questions