简体   繁体   English

Spring JPA数据存储库通用实现示例

[英]Spring JPA Data Repository Generic Implementation Example

Is it possible to create a generic Repository interface to save POJOs in my spring-data project? 是否可以创建一个通用的Repository接口来将POJO保存在我的spring-data项目中?

I have around 50 different objects and I don't want to create 50 corresponding repository interfaces one of each pojo ? 我大约有50个不同的对象,我不想为每个pojo之一创建50个相应的存储库接口吗?

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. 我认为唯一的方法是创建@NoBeanRepository因为Spring的存储库的主要目标是提供用户友好的界面来操纵实体。 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*//  
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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