[英]Spring Data JPA: Implementing Custom Repository Behavior with Specifications
我想創建一個具有自定義行為的Spring Data JPA存儲庫,並使用Specification實現該自定義行為。 我已經通過Spring Data JPA文檔在單個存儲庫中實現自定義行為來設置它,除了沒有在自定義存儲庫中使用Spring Data Specification的示例。 如果可能的話,如何做到這一點?
我沒有看到一種方法將某些內容注入到需要規范的自定義實現中。 我認為我會很棘手,並將存儲庫的CRUD存儲庫部分注入自定義部分,但這會導致循環實例化依賴。
我沒有使用QueryDSL。 謝謝。
我想靈感的主要來源可能是SimpleJpaRepository
如何處理規范。 要看的關鍵點是:
SimpleJpaRepository.getQuery(…)
- 它基本上是創建一個CriteriaQuery
並使用JPA Root
引導一個選擇。 后者是否適用於您的用例已經取決於您。 我認為前者肯定適用。 SimpleJpaRepository.applySpecificationToCriteria(…)
- 它基本上使用getQuery(…)
生成的工件(即Root
和CriteriaQuery
),並將給定的Specification
應用於這些工件。 這不是使用規范,所以不確定它是否與您相關,但我能夠注入自定義行為的一種方式如下,
基本結構:如下
一世。 為通用父實體之后建模的實體類集創建通用接口。 注意,這是可選的。 在我的情況下,我需要這種層次結構,但沒有必要
public interface GenericRepository<T> { // add any common methods to your entity hierarchy objects, // so that you don't have to repeat them in each of the children entities // since you will be extending from this interface }
II。 將特定存儲庫從泛型(步驟1)和JPARepository擴展為
public interface MySpecificEntityRepository extends GenericRepository<MySpecificEntity>, JpaRepository<MySpecificEntity, Long> { // add all methods based on column names, entity graphs or JPQL that you would like to // have here in addition to what's offered by JpaRepository }
III。 在服務實現類中使用上面的存儲庫
現在,Service類可能看起來像這樣,
public interface GenericService<T extends GenericEntity, ID extends Serializable> { // add specific methods you want to extend to user }
通用實現類可以如下,
public abstract class GenericServiceImpl<T extends GenericEntity, J extends JpaRepository<T, Long> & GenericRepository<T>> implements GenericService<T, Long> { // constructor takes in specific repository public GenericServiceImpl(J genericRepository) { // save this to local var } // using the above repository, specific methods are programmed }
具體的實現類可以
public class MySpecificEntityServiceImpl extends GenericServiceImpl<MySpecificEntity, MySpecificEntityRepository> implements MySpecificEntityService { // the specific repository is autowired @Autowired public MySpecificEntityServiceImpl(MySpecificEntityRepository genericRepository) { super(genericRepository); this.genericRepository = (MySpecificEntityRepository) genericRepository; } }
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.