Spring JPA: Using multiple projection on same query interface

前端 未结 2 1063
星月不相逢
星月不相逢 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:19

    So I've managed to figure out how to use multiple projections with a single query.

     T getByUsername(String username, Class 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 {
         T getByUsername(String username, Class 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)
    

提交回复
热议问题