Reputation: 86747
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?
Upvotes: 19
Views: 11713
Reputation: 4158
You can do something pretty similar, which I believe will achieve the result you're looking for.
STEPS NECESSARY:
UserRepo
will now extend 2 interfaces:
public interface UserRepo extends CrudRepository<User, Long>, UserCustomMethods{
}
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);
}
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
}
}
UserRepo
wherever you need, and enjoy both CRUD and your custom methods :)Upvotes: 21