Spring JPA: Using multiple projection on same query interface

前端 未结 2 993
星月不相逢
星月不相逢 2020-12-10 21:11

I am trying to use Spring JPA\'s projection to filter out unnecessary data from query result. However, I have multiple projections that will need to be used on the same inte

相关标签:
2条回答
  • 2020-12-10 21:16

    Just add something between get (or e.g. find) and By starting with an upper case character. It is ignored in the query generation.

    public interface UserRepository extends CrudRepository<UserAccount, Long> {
    
       AuthenticateProjection getByUsername(String username);
    
       UserDetailsProjection getAnotherByUsername(String username);
    
    }
    
    0 讨论(0)
  • 2020-12-10 21:19

    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)
    
    0 讨论(0)
提交回复
热议问题