I'm building a Spring Boot application containing more than 10 domain classes which need to be persisted in a SQL database. The problem is that I need to create an interface for every single domain class, so something like this for each one:
public interface BehandelaarRepo extends CrudRepository<BehandelCentrum, Long> {
}
Is there any way to decrease the number of repositories by using some kind of design pattern or whatever? Any suggestions?
You can actually make it some easier for yourself by using generics the same way Spring Data JPA does it:
The trick is that you can use all subclasses, and you're getting that class back as well. I always create one superclass, so I get rid of my ID generic:
I create my @Entity classes as a subclass from this JpaObject.
Second step: create my super interface for future usage of special queries:
Next step: the generic Dao which looks some stupid and remains empty at all times
Now have a sharp look at that save method in CrudRepository / JpaRepository:
Any object extending JpaObject (S extends JpaObject) now can be given as a parameter to all methods, and the returntype is the same class as your parameter.
(Aziz, als het handiger is, kan het ook in het Nederlands uitgelegd worden :P Groet uit Zwolle)
Well, I had a similar problem. I resolved it by creating new layer, namely RepositoryManager (or ModelService) singleton that had all the repo interfaces and methods that used them.
If you want you can implement generic save method (then call that class ModelService) that resolves model types through reflection and chooses the corresponding repository.
It was also handy for decoupling cache implementation (I used spring cache).