java - 如何在 Java 中使用泛型来更轻松地使用 JPA 存储库?
问题描述
我有一个名为 Select 的 Web 组件。它是 Vaadin 框架中的一个下拉框。我想在启动时构建选择下拉框,它们将包含来自 Spring Boot 中 JPA 存储库的数据。
这是我的示例代码:
private <T extends UserLoggRepository> void addSelect(Select<Long> select, String placeHolder, T repository) {
List<UserLogg> userLoggers = repository.findAll();
List<Long> items = new ArrayList<Long>();
for(int i = 0; i < userLoggers.size(); i++) {
long value = userLoggers.get(i).getLoggerId();
if(items.contains(value) == false)
items.add(value);
}
if(items.contains((long) 0) == false)
items.add((long) 0);
select.setItems(items);
select.setPlaceholder(placeHolder);
}
此代码有效!但是我有不同的实体和不同的存储库。我有实体:
- 用户日志
- 数据记录仪
- 校准记录
- 报警记录
我有存储库:
- 用户日志存储库
- 数据记录库
- 校准记录库
- AlarmLogg 存储库
问题:
如何更改方法addSelect
以便它们可以与连接到实体的任何存储库一起使用?所有存储库都有标准功能findAll()
,所有实体都有字段loggerId
。
重点:
我遇到的问题是此代码仅适用于实体UserLogg
和存储库UserLoggRepository
。
List<UserLogg> userLoggers = repository.findAll();
需要做什么:
这需要改变,但我不知道在这里写什么,所以它对他们来说变得更加普遍。
private <T extends UserLoggRepository> void addSelect
更新1:
JPA 中的存储库标头看起来像这样:
public interface AlarmLoggRepository extends JpaRepository<AlarmLogg, Long>
我可以使用它,但仍然得到了UserLogg
课程是固定的。
private <T extends JpaRepository<UserLogg, Long>> void addSelect(Select<Long> select, String placeHolder, T repository)
解决方案
If I understood your problem correctly, you can do inheritance and make a parent class for all your existing entities and change the definition of your addSelect method to return that parent class which could eventually return a type of any of it's subclasses.
For example, looks like your existing entities are all logs, so you can have an Abstract class named LoggRepository and have it extended by all your existing entities like:
public class UserLoggRepository extends LoggRepository
And then, update the method addSelect like below so it can return and of the subclasses of your parent abstract class LoggRepository
private <? extends LoggRepository> void addSelect(Select<Long> select, String placeHolder, T repository)
Hope this helps :)
推荐阅读
- android - EpoxyRecyclerview 中的更新项目(通知数据更改)
- sql - 这可能只使用 SQL 吗?
- android-studio - 为什么内部测试人员购买的 ın-app 订阅会在几分钟内从他们的帐户中消失
- amazon-web-services - AWS Lambda - 生成 PDF 问题
- reactjs - 在反应js钩子中调用.map内的新函数
- magento - Magento 2.4 管理员无效的父 id Dotdigitalgroup_Email::marketing_automation
- javascript - 无法使用 vue.js 和 axios 读取未定义的属性“帖子”
- c# - 如何解决 Get Endpoint ASP.Net API 中的滞后问题
- sass - 如何将 scss 移动到 svelte 3 中的新文件?
- docker - Buildpack - 保存图像:无法将图像写入以下标签