簡體   English   中英

Spring Data-如何在存儲庫片段中重用存儲庫?

[英]Spring Data - How to reuse repository in repository fragment?

更新 :以下使用Spring Boot 2.1.0

我有一個Spring Data存儲庫,並嘗試按照文檔中片段示例為其提供一些自定義功能。

因此,我向存儲庫添加了一個額外的接口:

public interface UserRepository extends JpaRepository<User, Long>, UserExtraLogic {
    User findByFirstNameAndLastName(String firstName, String lastName);
}

使用此自定義界面:

interface UserExtraLogic {
    void ensureHasAccess();
}

及其實現:

class UserExtraLogicImpl implements UserExtraLogic {
    public void ensureHasAccess() {
    }
}

問題是我希望能夠在UserExtraLogicImpl使用我的存儲庫,這樣我就可以重用findByFirstNameAndLastName類的查詢方法,而不必自己使用EntityManager編寫。 所以我嘗試了這個:

class UserExrtaLogicImpl implements UserExtraLogic {
    @Autowired
    private UserRepository userRepository;
}

但是隨后應用程序無法啟動。 我得到了NullPointerException,但我認為這只是Spring進入嘗試解決這些依賴關系的周期。

我想做的事可能嗎? 還有另一種方法嗎?

您可以使用ObjectFactory<T> (Spring概念)或Provider<T> (標准Java API)延遲加載存儲庫。

class UserExrtaLogicImpl implements UserExtraLogic {
    @Autowired
    private ObjectFactory<UserRepository> userRepository;

    public void soSomething() {
         userRepository().getObject().findById(xxx);
    }
}

我有完全相同的代碼模式,並且在最近的項目中遇到了相同的問題,最后通過使用@Lazy來懶惰初始化UserRepository來解決它:

class UserExrtaLogicImpl implements UserExtraLogic {

    @Lazy
    @Autowired
    private UserRepository userRepository;

}

倉庫啟用

文檔

如果您使用的是Spring XML配置,則應具有以下內容:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xmlns:jpa="http://www.springframework.org/schema/data/jpa"
  xsi:schemaLocation="http://www.springframework.org/schema/beans
    http://www.springframework.org/schema/beans/spring-beans.xsd
    http://www.springframework.org/schema/data/jpa
    http://www.springframework.org/schema/data/jpa/spring-jpa.xsd">

  <jpa:repositories base-package="com.acme.repositories" />

</beans>

如果您使用的是Java配置,則應具有以下配置:

@Configuration
@EnableJpaRepositories("com.acme.repositories")
class ApplicationConfiguration {

  @Bean
  EntityManagerFactory entityManagerFactory() {
    // …
  }
}

倉庫配置

另外,您需要在存儲庫上添加@Repository批注:

@Repository
public interface UserRepository extends JpaRepository<User, Long>, UserExtraLogic {
    User findByFirstNameAndLastName(String firstName, String lastName);
}

說明

文檔

使用repositories元素可以按“創建存儲庫實例”中所述查找Spring Data存儲 除此之外,它還為所有使用@Repository注釋的bean激活持久性異常轉換,以將JPA持久性提供程序引發的異常轉換為Spring的DataAccessException層次結構。

請在文檔中對此加以注意。

Extending the fragment interface with your repository interface combines the CRUD and custom functionality and makes it available to clients.

擴展片段接口時,最終的存儲庫也將包括該接口。 那是它的好處。 如果您想訪問原始存儲庫邏輯,我可以為您推薦3種方法。

  1. 在片段中添加查詢,然后在存儲庫中擴展查詢。 然后在您的服務方法中包括一個聚合方法。 用那種方法寫你的邏輯。
  2. 在自定義界面中,包括存儲庫,並且不要擴展存儲庫中的自定義接口。
  3. 使用裝飾器類。 將所有方法委托給存儲庫,並將自定義邏輯與存儲庫結合。

不要包括循環依賴,因為這不是一個好習慣。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM