使用泛型将自定义方法添加到JPARepository [英] Add Custom Method to JPARepository with Generics

查看:83
本文介绍了使用泛型将自定义方法添加到JPARepository的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有一个名为 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 Products). 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.

在Github上

如果您希望向所有存储库添加自定义行为,请参考

If you would rather add custom behaviour to all repositories, refer to the relevant section in the official documentation.

这篇关于使用泛型将自定义方法添加到JPARepository的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆