1 回答

TA貢獻1844條經驗 獲得超8個贊
首先,您定義所有自定義存儲庫將從中繼承的基本接口
@NoRepositoryBean
interface BaseJpaRepository<T, ID> extends JpaRepository<T, ID> {
? ? ?// You can also declare any generic methods here,?
? ? ?// and override (intercept) them in BaseJpaRepositoryImpl as well
}
它的實施也是如此
@NoRepositoryBean
class BaseJpaRepositoryImpl<T, ID>
? ? ? ? extends SimpleJpaRepository<T, ID>
? ? ? ? implements BaseJpaRepository<T, ID> {
? ? public BaseJpaRepositoryImpl(JpaEntityInformation<T, ID> entityInformation, EntityManager em) {
? ? ? ? super(entityInformation, em);
? ? }
? ? // One of 'defined' methods inherited from SimpleJpaRepository (and in turn from JpaRepository)
? ? @Override
? ? public List<T> findAll() {
? ? ? ? //run some code here
? ? ? ? List<T> res = super.findAll();
? ? ? ? //run some code here
? ? ? ? return res;
? ? }
? ? // other 'defined' methods to intercept ...
}
然后,您的自定義存儲庫將看起來像往常一樣,只是它現在是從您的BaseJpaRepository接口而不是 Spring 的接口派生的JpaRepository
@Repository
interface UserRepository extends BaseJpaRepository<User, Long> {
}
為了使其一切正常,讓我們修改以下注釋,該注釋通常放置在某個@Configuration類或@SpringBootApplication-ed 類上
@EnableJpaRepositories(
? ? ? ? basePackages = {"org.example.repositories"},
? ? ? ? repositoryBaseClass = BaseJpaRepositoryImpl.class
)
添加回答
舉報