使用Spring Data Projection进行过滤

时间:2018-06-15 14:45:36

标签: spring rest spring-data-jpa spring-data querydsl

我为Spring Data Repository创建了一个基于类的Projection。这很好用。然后我尝试使用QueryDSL中的@QueryProjection来注释构造函数,希望得到一个带有分页,排序和过滤的REST端点。

代码看起来像这样,但为了简洁,省略了更多字段和细节:

实体:

@Data
@Entity
public class Entity extends BaseEntity {
    private String fieldA, fieldB;
    private AnotherEntity ae;
}

DTO:

@Getter
@FieldDefaults(makeFinal = true, level = AccessLevel.PRIVATE)
public class EntityDto {
    private final String fieldA;
    private final String anotherEntityFieldC;

    @QueryProjection
    public EntityDto(final String fieldA, final String anotherEntityFieldC) {
        this.fieldA = fieldA;
        this.anotherEntityFieldC = anotherEntityFieldC;
    }
}

存储库:

public EntityRepo extends JpaRepository<Entity, Long>, QuerydslBinderCustomizer<EntityPath<Entity>>, QuerydslPredicateExecutor<Entity> {
    Page<EntityDto> findPageProjectedBy(Predicate predicate, Pageable pageable);
}

端点:

@RestController
@RequestMapping(EntityEndpoint.ROOT)
@RequiredArgsConstructor(onConstructor = @__({@Autowired}))
public EntityEndpoint {
    private final EntityRepo er;

    @GetMapping
    public ResponseEntity<PagedResources<Resource<EntityDto>>> getAllEntities(
        Pageable pageable, 
        @QuerydslPredicate(root = EntityDto@.class) Predicate predicate,
        PagedResourcesAssembler<EntityDto> assembler) {
            Page<EntityDto> page = er.findPageProjectedBy(predicate, pageable);
            return new ResponseEntity<>(assembler.toResource(page), HttpStatus.OK);
    }
}

我得到例外:

  

java.lang.IllegalStateException:在类at.dataphone.logis4.model.dto.QBuchungDto中找不到相同类型的静态字段!

Stacktrace as gist

这就是网址:

  

curl -X GET --header'Eccept:application / json''http://localhost:8080/Entity'

1 个答案:

答案 0 :(得分:0)

好吧,看来您只能使用实际的实体进行查询。

我认为它是“ WHERE”子句的一部分,该子句实际上只能在所选实体中具有列,而DTO投影发生在“ SELECT”子句中。

@QueryProjection注释似乎仅用于QueryDsl代码生成器标记类,然后可以将其用于create projections in a select-clause