具有扩展接口和泛型的动态JPA投影

时间:2019-09-12 02:07:15

标签: spring generics spring-data-jpa spring-projections

我正在寻找使用Spring JPA动态投影来限制查询返回的字段数。我正在使用的表很宽,但投影仍然包含大约10个字段。因此,我正在尝试使用动态投影。问题似乎在于尝试在存储库接口中指定方法,因为我首先有一个使用抽象类扩展JpaRepository的接口,然后又有了一个使用实际类对该接口进行扩展的接口。

我尝试了各种方法来限制字段数,而这种方法似乎与我想使用的方法最接近。

这是我在抽象类User上的存储库:

@NoRepositoryBean
public interface UserRepository <T extends User> extends JpaRepository<T, 
Long>{

    <S extends T> S findByLoginName(String loginName);

}

这是我在实际类ConcreteUser上的实际存储库:

@Repository
public interface ConcreteUserRepository extends UserRepository<ConcreteUser> {

}

在我的服务类实现中,我有一个如下所示的方法调用:

ConcreteUser user = this.userRepository.findByLoginName(loginName);

这当然会返回大量字段,因此我创建了一个接口,其中包含我要称为UserProfile的字段子集。字段名称与ConcreteUser中的名称完全相同。然后,我在用户类中添加了“实现UserProfile”。我不知道这是否有必要,但我正在尝试使泛型工作,以便我可以执行以下操作:

@NoRepositoryBean
public interface UserRepository <T extends User> extends JpaRepository<T, 
Long>{

    <S extends T> S findByLoginName(String loginName, Class<S> clazz);

}

然后这样称呼它:

ConcreteUser user = this.userRepository.findByLoginName(loginName, ConcreteUser.class);
UserProfile profile = this.userRepository.findByLoginName(loginName, UserProfile.class;

我已经尝试了多种使用泛型的方法。我还尝试过使用DTO类UserProfileDTO代替UserProfile接口。

由于额外的抽象级别,我无法正确使用泛型。

0 个答案:

没有答案