使用泛型将自定义方法添加到JPARepository [英] Add Custom Method to JPARepository with Generics
问题描述
假设我有一个名为 Product
的实体.我将回购设计为
Assume I have a Entity called Product
. I design a Repo as
@Repository
interface ProductRepository implements JPARepository<Product, Integer>{}
这将继承所有默认方法,例如 save,findAll
等;
This would inherit all the default methods such as save, findAll
etc;
现在我想拥有一个自定义方法,这也是其他实体的常用方法.我添加了另一个接口和实现
Now I want to have one custom method, which is also a common method for other entities. I added another interface and implementation
interface CustomRepository<T,ID>{ public void customMethod() }
class CustomRepositoryImpl implements CustomRepository<T,ID>{ public void customMethod(){} }
然后我将ProductRepository重写为
And I rewrite the ProductRepository as
@Repository
interface ProductRepository implements
JPARepository<Product, Integer>,
CustomRepository<Product, Integer>
{}
现在,这不会给我任何编译错误.但是在运行时,出现此错误:
Now, this does not give me any compilation error. But during runtime, I get this error:
找不到产品的属性"customMethod"
No property 'customMethod' is found for Product
我想念什么?
推荐答案
您似乎正在尝试将自定义行为添加到单个存储库(即 ProductRepository
)中.但是,代码的结构好像需要将自定义行为添加到所有存储库中( CustomRepository
并非特定于 Product
s).因此,错误.
You seem to be trying to add custom behaviour to a single repository, namely ProductRepository
. However, the code is structured as if custom behaviour needs to be added to all repositories (CustomRepository
is not specific to Product
s). Hence, the error.
步骤1 :声明一个自定义存储库
Step 1: Declare a custom repository
interface CustomRepository<T, ID extends Serializable> {
void customMethod();
}
第2步:将自定义行为添加到所需的存储库
Step 2: Add custom behaviour to the required repository
interface ProductRepository extends CrudRepository<Product, Integer>
, CustomRepository<Product, Integer> {}
第3步:添加特定于
Product
的实现
class ProductRepositoryImpl implements CustomRepository<Product, Integer> { ... }
注意:该类必须命名为 ProductRepositoryImpl
,Spring Data JPA管道才能自动将其拾取.
Note: The class must be named ProductRepositoryImpl
for Spring Data JPA plumbing to pick it up automatically.
If you would rather add custom behaviour to all repositories, refer to the relevant section in the official documentation.
这篇关于使用泛型将自定义方法添加到JPARepository的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!