mayur tanna
mayur tanna

Reputation: 251

Spring JPA Data Repository Generic Implementation Example

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.

Upvotes: 4

Views: 2120

Answers (1)

Yuriy Tsarkov
Yuriy Tsarkov

Reputation: 2568

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*//  
}

Upvotes: 1

Related Questions