4

Is it possible to create a generic Repository interface to save POJOs in my spring-data project?

I have around 50 different objects and I don't want to create 50 corresponding repository interfaces one of each pojo ?

For example,

public interface FooRepository extends JpaRepository<Foo, Integer> { }

public interface BarRepository extends JpaRepository<Bar, Integer> { }

and so on...

I do see similar questions on this site but not having a really good example.

Thanks in advance for any help.

Phenomenal One
  • 2,501
  • 4
  • 19
  • 29
mayur tanna
  • 241
  • 1
  • 3
  • 14
  • Have you considered a solution proposed in this [question](https://stackoverflow.com/questions/25187532/how-to-declare-repositories-based-on-entity-interfaces)? – Boris Sep 18 '18 at 15:09

1 Answers1

1

I think the only way is to create a @NoBeanRepository because the main goal of a Spring's repository is to provide a user-friendly interface to manipulate entities. But in this case your entities must have same properties.

@NoRepositoryBean
public interface SortOrderRelatedEntityRepository<T, ID extends Serializable>
    extends SortOrderRelatedEntityRepository<T, ID> {

  T findOneById(Long id);   

  List<T> findByParentIdIsNullAndSortOrderLessThanEqual(Integer sortOrder);

  /** and so on*//
}

public interface StructureRepository
    extends SortOrderRelatedEntityRepository<Structure, Long> {

  Structure findOneById(Long id);

  List<Structure> findByParentIdIsNullAndSortOrderLessThanEqual(Integer sortOrder);

  /** and so on*//  
}
Phenomenal One
  • 2,501
  • 4
  • 19
  • 29
Yuriy Tsarkov
  • 2,461
  • 2
  • 14
  • 28
  • Thanks for the answer. In case of @NoRepositoryBean also, I need to create corresponding interfaces for each pojo right ? Like you have created one for Structure ? – mayur tanna Sep 19 '18 at 06:43
  • yes, you have to. Actually you can't create a thing that you want. – Yuriy Tsarkov Sep 19 '18 at 07:59
  • One more remark: It really depends on what you are trying to achive. First way is DO NOT create any repositories. This way is unreacheble with standard Spring libs. The second way is somehow to abstractise you calls to a repositories - this is a way I showed you before. In this case you must create repo for the each entity but there are ways to 'trick' Spring and call them in a single bean – Yuriy Tsarkov Sep 19 '18 at 14:31