自定義 Repository 實現

Spring Data 提供了各種選項,可以透過少量編碼來建立查詢方法。但是,當這些選項不符合您的需求時,您還可以為 repository 方法提供自己的自定義實現。本節描述瞭如何實現。

自定義單個 Repository

要使用自定義功能豐富 repository,您必須首先定義一個片段介面和自定義功能的實現,如下所示:

用於自定義 repository 功能的介面
interface CustomizedUserRepository {
  void someCustomMethod(User user);
}
自定義 repository 功能的實現
class CustomizedUserRepositoryImpl implements CustomizedUserRepository {

  @Override
  public void someCustomMethod(User user) {
    // Your custom implementation
  }
}

與片段介面對應的類名最重要的部分是 Impl 字尾。您可以透過設定 @Enable<StoreModule>Repositories(repositoryImplementationPostfix = …) 來定製特定於儲存的字尾。

從歷史上看,Spring Data 自定義 repository 實現發現遵循命名模式,該模式從 repository 派生自定義實現類名,從而有效地允許單個自定義實現。

位於與 repository 介面相同的包中、與*repository 介面名稱*後跟*實現字尾*匹配的型別被視為自定義實現,並將作為自定義實現進行處理。遵循該名稱的類可能會導致意外行為。

我們認為單個自定義實現命名已棄用,建議不要使用此模式。相反,請遷移到基於片段的程式設計模型。

實現本身不依賴於 Spring Data,可以是常規的 Spring bean。因此,您可以使用標準的依賴注入行為來注入對其他 bean 的引用(例如 JdbcTemplate),參與方面等。

然後,您可以讓您的 repository 介面擴充套件片段介面,如下所示:

您的 repository 介面的更改
interface UserRepository extends CrudRepository<User, Long>, CustomizedUserRepository {

  // Declare query methods here
}

透過您的 repository 介面擴充套件片段介面,將 CRUD 和自定義功能結合起來,並使其可供客戶端使用。

Spring Data repository 透過使用形成 repository 組合的片段來實現。片段是基本 repository、功能方面(例如 Querydsl)以及自定義介面及其實現。每次您向 repository 介面新增介面時,您都透過新增片段來增強組合。基本 repository 和 repository 方面實現由每個 Spring Data 模組提供。

以下示例顯示了自定義介面及其實現:

片段及其實現
interface HumanRepository {
  void someHumanMethod(User user);
}

class HumanRepositoryImpl implements HumanRepository {

  @Override
  public void someHumanMethod(User user) {
    // Your custom implementation
  }
}

interface ContactRepository {

  void someContactMethod(User user);

  User anotherContactMethod(User user);
}

class ContactRepositoryImpl implements ContactRepository {

  @Override
  public void someContactMethod(User user) {
    // Your custom implementation
  }

  @Override
  public User anotherContactMethod(User user) {
    // Your custom implementation
  }
}

以下示例顯示了擴充套件 CrudRepository 的自定義 repository 的介面:

您的 repository 介面的更改
interface UserRepository extends CrudRepository<User, Long>, HumanRepository, ContactRepository {

  // Declare query methods here
}

Repository 可以由多個自定義實現組成,這些實現按照它們的宣告順序匯入。自定義實現的優先順序高於基本實現和 repository 方面。此順序允許您覆蓋基本 repository 和方面方法,並在兩個片段貢獻相同方法簽名時解決歧義。Repository 片段不限於在單個 repository 介面中使用。多個 repository 可以使用一個片段介面,從而允許您在不同的 repository 之間重用自定義。

以下示例顯示了 repository 片段及其實現:

覆蓋 save(…) 的片段
interface CustomizedSave<T> {
  <S extends T> S save(S entity);
}

class CustomizedSaveImpl<T> implements CustomizedSave<T> {

  @Override
  public <S extends T> S save(S entity) {
    // Your custom implementation
  }
}

以下示例顯示了使用前面 repository 片段的 repository:

自定義的 repository 介面
interface UserRepository extends CrudRepository<User, Long>, CustomizedSave<User> {
}

interface PersonRepository extends CrudRepository<Person, Long>, CustomizedSave<Person> {
}

配置

repository 基礎設施嘗試透過掃描在其找到 repository 的包下的類來自動檢測自定義實現片段。這些類需要遵循附加字尾(預設為 Impl)的命名約定。

以下示例顯示了使用預設字尾的 repository 和為字尾設定自定義值的 repository:

示例 1. 配置示例
  • Java

  • XML

@EnableRedisRepositories(repositoryImplementationPostfix = "MyPostfix")
class Configuration { … }
<repositories base-package="com.acme.repository" />

<repositories base-package="com.acme.repository" repository-impl-postfix="MyPostfix" />

前面示例中的第一個配置嘗試查詢名為 com.acme.repository.CustomizedUserRepositoryImpl 的類作為自定義 repository 實現。第二個示例嘗試查詢 com.acme.repository.CustomizedUserRepositoryMyPostfix

歧義解決

如果在不同的包中找到多個具有匹配類名的實現,Spring Data 會使用 bean 名稱來標識要使用哪一個。

給定前面所示的 CustomizedUserRepository 的以下兩個自定義實現,將使用第一個實現。其 bean 名稱為 customizedUserRepositoryImpl,它與片段介面(CustomizedUserRepository)加上字尾 Impl 的名稱匹配。

示例 2. 解決模糊實現
class CustomizedUserRepositoryImpl implements CustomizedUserRepository {

  // Your custom implementation
}
@Component("specialCustomImpl")
class CustomizedUserRepositoryImpl implements CustomizedUserRepository {

  // Your custom implementation
}

如果您用 @Component("specialCustom") 註解 UserRepository 介面,則 bean 名稱加上 Impl 將與 com.acme.impl.two 中為 repository 實現定義的名稱匹配,並且將使用它而不是第一個。

手動裝配

如果您的自定義實現僅使用基於註解的配置和自動裝配,則前面所示的方法工作良好,因為它被視為任何其他 Spring bean。如果您的實現片段 bean 需要特殊裝配,您可以按照上一節中描述的約定宣告 bean 並命名它。然後,基礎設施將透過名稱引用手動定義的 bean 定義,而不是自行建立。以下示例顯示瞭如何手動裝配自定義實現:

示例 3. 手動裝配自定義實現
  • Java

  • XML

class MyClass {
  MyClass(@Qualifier("userRepositoryImpl") UserRepository userRepository) {
    …
  }
}
<repositories base-package="com.acme.repository" />

<beans:bean id="userRepositoryImpl" class="…">
  <!-- further configuration -->
</beans:bean>

使用 spring.factories 註冊片段

配置一節中已經提到的,基礎設施僅自動檢測 repository 基本包中的片段。因此,如果片段位於其他位置或希望由外部存檔貢獻,如果它們不共享共同的名稱空間,則不會找到它們。在 spring.factories 中註冊片段允許您規避此限制,如下一節所述。

想象一下,您希望為您的組織提供一些可跨多個 repository 使用的自定義搜尋功能,利用文字搜尋索引。

首先,您需要的是片段介面。請注意通用 <T> 引數,以使片段與 repository 域型別對齊。

片段介面
public interface SearchExtension<T> {

    List<T> search(String text, Limit limit);
}

假設實際的全文搜尋可透過 SearchService 獲得,該服務在上下文中註冊為 Bean,因此您可以在我們的 SearchExtension 實現中消費它。執行搜尋所需的一切是集合(或索引)名稱和一個物件對映器,它將搜尋結果轉換為實際的域物件,如下所示。

片段實現
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Limit;
import org.springframework.data.repository.core.RepositoryMethodContext;

class DefaultSearchExtension<T> implements SearchExtension<T> {

    private final SearchService service;

    DefaultSearchExtension(SearchService service) {
        this.service = service;
    }

    @Override
    public List<T> search(String text, Limit limit) {
        return search(RepositoryMethodContext.getContext(), text, limit);
    }

    List<T> search(RepositoryMethodContext metadata, String text, Limit limit) {

        Class<T> domainType = metadata.getRepository().getDomainType();

        String indexName = domainType.getSimpleName().toLowerCase();
        List<String> jsonResult = service.search(indexName, text, 0, limit.max());

        return jsonResult.stream().map(…).collect(toList());
    }
}

在上面的示例中,RepositoryMethodContext.getContext() 用於檢索實際方法呼叫的元資料。RepositoryMethodContext 公開了附加到 repository 的資訊,例如域型別。在這種情況下,我們使用 repository 域型別來標識要搜尋的索引名稱。

暴露呼叫元資料是昂貴的,因此預設情況下它是停用的。要訪問 RepositoryMethodContext.getContext(),您需要建議負責建立實際 repository 的 repository 工廠來暴露方法元資料。

暴露 Repository 元資料
  • 標記介面

  • Bean Post Processor

向片段實現新增 RepositoryMetadataAccess 標記介面將觸發基礎設施,併為那些使用該片段的 repository 啟用元資料暴露。

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Limit;
import org.springframework.data.repository.core.support.RepositoryMetadataAccess;
import org.springframework.data.repository.core.RepositoryMethodContext;

class DefaultSearchExtension<T> implements SearchExtension<T>, RepositoryMetadataAccess {

    // ...
}

exposeMetadata 標誌可以透過 BeanPostProcessor 直接在 repository 工廠 bean 上設定。

import org.springframework.beans.factory.config.BeanPostProcessor;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.repository.core.support.RepositoryFactoryBeanSupport;

@Configuration
class MyConfiguration {

    @Bean
    static BeanPostProcessor exposeMethodMetadata() {

        return new BeanPostProcessor() {

            @Override
            public Object postProcessBeforeInitialization(Object bean, String beanName) {

                if(bean instanceof RepositoryFactoryBeanSupport<?,?,?> factoryBean) {
                    factoryBean.setExposeMetadata(true);
                }
                return bean;
            }
        };
    }
}

請不要只是複製/貼上上面的內容,而是考慮您的實際用例,這可能需要更細粒度的方法,因為上面只會簡單地為每個 repository 啟用該標誌。

擁有片段宣告和實現後,您可以在 META-INF/spring.factories 檔案中註冊擴充套件,並根據需要打包。

META-INF/spring.factories 中註冊片段
com.acme.search.SearchExtension=com.acme.search.DefaultSearchExtension

現在您已準備好使用您的擴充套件;只需將介面新增到您的 repository。

使用它
import com.acme.search.SearchExtension;
import org.springframework.data.repository.CrudRepository;

interface MovieRepository extends CrudRepository<Movie, String>, SearchExtension<Movie> {

}

自定義基本 Repository

上一節中描述的方法要求在您想要自定義基本 repository 行為以使所有 repository 都受到影響時,對每個 repository 介面進行自定義。要更改所有 repository 的行為,您可以建立一個擴充套件持久化技術特定 repository 基類的實現。然後,此類的作用是 repository 代理的自定義基類,如以下示例所示:

自定義 repository 基類
class MyRepositoryImpl<T, ID>
  extends SimpleJpaRepository<T, ID> {

  private final EntityManager entityManager;

  MyRepositoryImpl(JpaEntityInformation entityInformation,
                          EntityManager entityManager) {
    super(entityInformation, entityManager);

    // Keep the EntityManager around to used from the newly introduced methods.
    this.entityManager = entityManager;
  }

  @Override
  @Transactional
  public <S extends T> S save(S entity) {
    // implementation goes here
  }
}
該類需要具有其父類的建構函式,儲存特定的 repository 工廠實現會使用該建構函式。如果 repository 基類有多個建構函式,則覆蓋接受 EntityInformation 以及特定於儲存的基礎設施物件(例如 EntityManager 或模板類)的建構函式。

最後一步是使 Spring Data 基礎設施瞭解自定義的 repository 基類。在配置中,您可以使用 repositoryBaseClass 來實現,如以下示例所示:

示例 4. 配置自定義 repository 基類
  • Java

  • XML

@Configuration
@EnableRedisRepositories(repositoryBaseClass = MyRepositoryImpl.class)
class ApplicationConfiguration { … }
<repositories base-package="com.acme.repository"
     base-class="….MyRepositoryImpl" />
© . This site is unofficial and not affiliated with VMware.