Skip to content
Advertisement

How to implement only specific method of CrudRepository in Spring?

I’m using CrudRepository of spring-data-jpa to just define an interface of an entity and then having all standard crud methods without having to provide an implementation explicitly, eg:

public interface UserRepo extends CrudRepository<User, Long> {

}

Though now I’d like to override only the save() method in my custom implementation. How could I achieve this? Because, if I implement the interface UserRepo, I’d have to implement all other CRUD methods that are inherited from interface CrudRepository.

Can’t I write my own implementation that has all CRUD methods but overriding only one without having to implement all others myself?

Advertisement

Answer

You can do something pretty similar, which I believe will achieve the result you’re looking for.

STEPS NECESSARY:

  1. UserRepo will now extend 2 interfaces:

     public interface UserRepo extends CrudRepository<User, Long>, UserCustomMethods{
    
     }
    
    
  2. Create a new interface named UserCustomMethods (you can choose the name and change both here and in step 1)

     public interface UserCustomMethods{
         public void mySave(User... users);
    
     }
    
    
  3. create a new class named UserRepoImpl (here the name does matter and it should be RepositoryNameImpl, because if you call it something else, you will need to adjust the Java/XML configuration accordingly). this class should implement only the CUSTOM interface you’ve created.

TIP: you can inject entitymanager in this class for your queries

public class UserRepoImpl implements UserRepo {
    
    //This is my tip, but not a must...
    @PersistenceContext
    private EntityManager em;

    public void mySave(User... users){
        //do what you need here
    }
}

  1. Inject UserRepo wherever you need, and enjoy both CRUD and your custom methods 🙂
User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement