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?
To exclude an interface extending Repository from being instantiated as a repository instance it can either be annotate it with @NoRepositoryBean or moved out side of the configured base-package .
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 :)If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With