So I've managed to figure out how to use multiple projections with a
single query.
<T> T getByUsername(String username, Class<T> projection) This allows the method caller to specified the type of projection to be
applied to the query.
To further improve this so it is less prone to error, I made a blank
interface that the projection will have to extend in order to be able
to insert class into the parameter.
public interface JPAProjection {
}
public interface UserRepository extends CrudRepository<UserAccount, Long> {
<T extends JPAProjection > T getByUsername(String username, Class<? extends JPAProjection> projection);
}
Projection Interface
public interface UserDetailsProjection extends JPAProjection{
@Value("#{target.username}")
String getUsername();
@Value("#{target.firstname}")
String getFirstname();
@Value("#{target.lastname}")
String getLastname();
}
Then I can call the query method by
getByUsername("...", UserDetailsProjection.class)
@Query
不是一个注解,你想绕过默认的解决方案。无论如何,你都需要做一些事情来返回你想要的数据子集,使用默认的方式可以在进行查询时重复使用,而不必每次都创建许多不同的构造函数。 - M. Deinum