【问题标题】:Filtering with Spring Data Projection使用 Spring Data Projection 进行过滤
【发布时间】:2018-11-25 10:26:56
【问题描述】:

我为我的 Spring Data Repository 创建了一个基于类的 Projection。这很好用。然后我尝试用 QueryDSL 中的@QueryProjection 对构造函数进行注解,希望得到一个具有分页、排序和过滤功能的 REST Endpoint。

代码如下所示,但为简洁起见,省略了更多字段和细节:

实体:

@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 'Accept: application/json' 'http://localhost:8080/Entity'

【问题讨论】:

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


    【解决方案1】:

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

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

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

    【讨论】:

      猜你喜欢
      • 2020-05-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-12-15
      • 2018-10-15
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多