Dynamic JPA Projections with extended interface and generics

800 Views Asked by At

I am looking to use Spring JPA Dynamic Projections to limit the number of fields returned from queries. The table I'm using is wide, but the projection still contains around 10 fields. Therefore I am trying to use Dynamic Projections. The problem seems to be with trying to specify the methods in the repository interface since I first have an interface that extends the JpaRepository using an abstract class and then I have an interface the extends that one using the actual class.

I have tried various approaches to limiting the number of fields and this one seems to be the closest to what I want to use.

Here is my repository on the abstract class User:

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

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

}

Here is my actual repository on the actual class ConcreteUser:

@Repository
public interface ConcreteUserRepository extends UserRepository<ConcreteUser> {

}

In my service class implementation I have a method call that looks like this:

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

This of course returns a large number of fields, so I created an interface that contains the subset of fields that I want called UserProfile. The field names are exactly the same as those in the ConcreteUser. I then added 'implements UserProfile' to the User class. I don't know if that is necessary, but I'm trying to get the generics working so that I can do something like this:

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

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

}

and then call it like this:

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

I've tried various approaches with the generics. I've also tried using my DTO class UserProfileDTO instead of the UserProfile interface.

I am having problems with getting the Generics correct because of the extra level of abstraction.

0

There are 0 best solutions below