Spring Boot: How to avoid too many JPA repositorie

2019-06-11 05:39发布

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?

2条回答
手持菜刀,她持情操
2楼-- · 2019-06-11 06:11

You can actually make it some easier for yourself by using generics the same way Spring Data JPA does it:

public interface JpaRepository<T extends Serializable, ID extends Serializable> {
    public <S extends T> S save(S object);
}

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:

@MappedSuperclass
public class JpaObject {
    @Id
    @GeneratedValue
    private Long id;
    (.... created, last updated, general stuff here....)
}

I create my @Entity classes as a subclass from this JpaObject.

Second step: create my super interface for future usage of special queries:

@NoRepositoryBean
public interface Dao<T extends JpaObject> extends JpaRepository<T, Long> {
}

Next step: the generic Dao which looks some stupid and remains empty at all times

@Repository
public interface GenericDao extends Dao<JpaObject> {
}

Now have a sharp look at that save method in CrudRepository / JpaRepository:

public <S extends T> S save(S object);

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)

查看更多
我欲成王,谁敢阻挡
3楼-- · 2019-06-11 06:12

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).

查看更多
登录 后发表回答