首页 > 解决方案 > 如何在 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); 
    }

此代码有效!但是我有不同的实体和不同的存储库。我有实体:

我有存储库:

问题:

如何更改方法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)

标签: javaspring-bootjpavaadin

解决方案


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 :)


推荐阅读