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
)
添加回答
举报