Java Spring数据JPA:JPA实体和存储库类上的包装器类

Java Spring数据JPA:JPA实体和存储库类上的包装器类,java,generics,spring-data-jpa,Java,Generics,Spring Data Jpa,我有两个JPA实体(Product,ProductCustomer)及其对应的JPA存储库(ProductRepository,ProductCustomerRepository)。我的用例是调用这两个存储库的findAll()方法,并将结果集写入excel 我不想自动连接每个存储库(存储库将来可能会增长)并调用findAll方法,而是想用一个通用对象包装实体对象和存储库对象,该对象将用于调用每个存储库的findAll方法 例如: public class GenericEntity { }

我有两个JPA实体(Product,ProductCustomer)及其对应的JPA存储库(ProductRepository,ProductCustomerRepository)。我的用例是调用这两个存储库的findAll()方法,并将结果集写入excel

我不想自动连接每个存储库(存储库将来可能会增长)并调用findAll方法,而是想用一个通用对象包装实体对象和存储库对象,该对象将用于调用每个存储库的findAll方法

例如:

public class GenericEntity {

}

@Entity
@Table(name="Product")
public class Product extends GenericEntity{
}
一般报告:

public interface GenericRepository<T extends GenericEntity> extends JpaRepository<T, Integer> {
}
公共接口GenericRepository扩展了JpaRepository{
}
产品存储库:

public interface ProductRepository extends GenericRepository<Product>{
}
公共接口ProductRepository扩展了GenericRepository{
}
启动期间执行方法:

    GenericRepository repo = (GenericRepository) context.getBean("productRepository");

List<GenericEntity> dataList = repo.findAll();
GenericRepository repo=(GenericRepository)context.getBean(“productRepository”);
List dataList=repo.findAll();

当我尝试这样做时,JPA希望包装器(GenericeEntity)上有@Entity和@Id注释。是否有任何方法可以使用Java泛型实现此用例?

no。Jpa在运行时读取注释,泛型在编译时存在。这种设置对于任何潜在的好处来说都是非常复杂的。如果您不想在一组服务中自动连接一组repo,您可以创建一个复合服务,自动连接所有repo,然后在整个应用程序中自动连接复合服务。按名称而不是通过自动连接来获取存储库bean有什么好处,我将扫描带有存储库的包,并将其存储在静态列表或映射中,这段代码将在静态块中执行。然后,我将迭代集合以调用每个存储库的findAll()方法,在excel中写入每个记录,并继续处理其他存储库。GenericRepository repo=(GenericRepository)context.getBean(“productRepository”);将替换为GenericRepository repo=(GenericRepository)context.getBean(repositr);我希望避免编写每个存储库的findAll()调用,然后将结果集写入excel