简体   繁体   中英

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM