java—如何存储和检索泛型类型

iqih9akk  于 2021-07-06  发布在  Java
关注(0)|答案(0)|浏览(236)

我有一个基本存储库接口和几个扩展它的存储库接口

interface VehicleRepository<T extends Vehicle> extends JpaRepository<T, Long>, JpaSpecificationExecutor<T> {
}
interface CarRepository extends VehicleRepository<Car> {
}
interface BikeRepository extends VehicleRepository<Bike> {
}

我也有几个jpa规范

class Specification<T extends Vehicle> implements Specification<T>{
}
class CarSpecification extends Specification<Car> {
}
class BikeSpecification extends Specification<Bike> {
}

现在我有了一个方法,可以接受不同的子类型 Vehicle 我想让他们各自打电话 Repository 以及 Specification . 我该怎么做?
我试过把它们包起来 List<VehicleRepository<**SOMETHING**>> repoList 以及 List<Specification<**SOMETHING**>> specList ,并希望根据输入调用它们

public class MyController {
    // @Autowire

    List<VehicleRepository<SOMETHING>> repoList;
    List<Specification<SOMETHING>> specList;

    @GetMapping("...")
    public ResponseEntity<List<? extends Vehicle>> getRawEventByCriteria(int vehicleType) {

        // What I am doing...
        if(vehicleType == 0) {
            List<Car> carList = ((VehicleRepository<Car>)repoList.get(0))
                .findAll((Specification<Car>)specList.get(0));
        } else if (vehicleType == 1) {
            List<Bike> bikeList = ((VehicleRepository<Bike>)repoList.get(1))
                .findAll((Specification<Bike>)specList.get(1));
        } else if (...) {
        }

        // What I want to do...
        List<vehicle.class> carList = ((AUTO SOMETHING)repoList.get(vehicleType))
            .findAll((AUTO SOMETHING)specList.get(vehicleType));

        return new ResponseEntity<>(retval, HttpStatus.OK);
    }
}

供参考, findAll() 定义如下

interface JpaSpecificationExecutor<T> {
    List<T> findAll(@Nullable Specification<T> spec);
}

目前,我离开的东西作为一个rawtype,它的作品没有我必须投一切,但我觉得这不是一个好办法。

暂无答案!

目前还没有任何答案,快来回答吧!

相关问题