QueryDslMongoRepository投影

时间:2013-12-11 15:05:15

标签: mongodb spring-data querydsl

我正在使用带有querydsl的mongodb的spring-data。 我有一个存储库

public interface DocumentRepository extends MongoRepository<Document, String> ,QueryDslPredicateExecutor<Document> {}

和实体

@QueryEntity
public class Document {

private String id;
private String name;
private String description;
private boolean locked;
private String message;

}

我需要加载包含id和name信息的文档列表。 因此,只应在我的实体中加载和设置id和name。 我认为查询投影是正确的。 这支持了吗?

另外我需要实现一些延迟加载逻辑。 存储库中有“跳过”和“限制”功能吗?

4 个答案:

答案 0 :(得分:3)

这有很多方面,不幸的是 - 不是一个问题,而是多个问题。

对于投影,您只需使用fields注释的@Query属性:

interface DocumentRepository extends MongoRepository<Document, String>, QuerydslPredicateExecutor<Document> {

  @Query(value = "{}", fields = "{ 'id' : 1, 'name' : 1 }")
  List<Document> findDocumentsProjected();
}

您可以将此与查询派生机制(通过不设置query),分页(见下文)甚至返回子句中的专用投影类型(例如DocumentExcerpt仅{ {1}}和id字段)。

存储库抽象完全支持分页。您已经通过扩展基接口获得了name和Querydsl特定版本的方法。您还可以在finder方法中使用分页API,添加findAll(Pageable)作为参数并返回Pageable

Page

reference documentation中了解详情。

答案 1 :(得分:1)

投影

对于我所知,默认的Spring Data存储库不支持预测。如果您想确保只将投影从数据库发送到您的应用程序(例如出于性能原因),您必须自己实现相应的查询。将自定义方法添加到标准仓库的扩展中应该不会太费力。

如果您只想隐藏某个调用应用程序的客户端的某些字段的内容,您通常会使用另一组实体对象,其间具有合适的映射。对不同级别的详细信息使用相同的POJO总是令人困惑,因为您不知道某个字段是否实际为null,或者该值是否仅在某个上下文中被抑制。

分页

我目前无法测试任何代码,但根据QueryDslPredicateExecutor的文档,方法findAll(谓词,可分页)应该是您想要的:

  • 它会为Page
  • 返回一个Iterable对象,该对象是常规Document
  • 您必须将Pageable传递给您,例如{使用PageRequest;将其初始化为已知的跳过和限制值应该是微不足道的

答案 2 :(得分:0)

我也为JPA找到了这种方法

Spring Data JPA and Querydsl to fetch subset of columns using bean/constructor projection

我目前正在尝试为MongoDB实现此功能。

答案 3 :(得分:0)

根据这个答案 - &gt; Question&lt; - 我实施了以下解决方案。

<强>实体

@QueryEntity
public class Document extends AbstractObject {
}

自定义QuerydslMongoRepository

public interface CustomQuerydslMongoRepository<T extends AbstractObject,ID extends Serializable> extends MongoRepository<T, ID> ,QueryDslPredicateExecutor<T>{
    Page<T> findAll(Predicate predicate, Pageable pageable,Path... paths);
    Page<T> findAll(Predicate predicate, Pageable pageable,List<Path> projections);

}

自定义QuerydslMongoRepository实施

public class CustomQuerydslMongoRepositoryImpl<T extends AbstractObject,ID extends Serializable> extends QueryDslMongoRepository<T,ID> implements CustomQuerydslMongoRepository<T,ID> {

    //All instance variables are available in super, but they are private
    private static final EntityPathResolver DEFAULT_ENTITY_PATH_RESOLVER = SimpleEntityPathResolver.INSTANCE;


    private final EntityPath<T> path;
    private final PathBuilder<T> pathBuilder;
    private final MongoOperations mongoOperations;
    public CustomQuerydslMongoRepositoryImpl(MongoEntityInformation<T, ID> entityInformation, MongoOperations mongoOperations) {
        this(entityInformation, mongoOperations,DEFAULT_ENTITY_PATH_RESOLVER);
    }

    public CustomQuerydslMongoRepositoryImpl(MongoEntityInformation<T, ID> entityInformation, MongoOperations mongoOperations, EntityPathResolver resolver) {
        super(entityInformation, mongoOperations, resolver);
        this.path=resolver.createPath(entityInformation.getJavaType());
        this.pathBuilder = new PathBuilder<T>(path.getType(), path.getMetadata());
        this.mongoOperations=mongoOperations;
    }

    @Override
    public Page<T> findAll( Predicate predicate, Pageable pageable,Path... paths) {
        Class<T> domainType = getEntityInformation().getJavaType();
        MongodbQuery<T> query = new SpringDataMongodbQuery<T>(mongoOperations, domainType);
        long total = query.count();
        List<T> content = total > pageable.getOffset() ? query.where(predicate).list(paths) : Collections.<T>emptyList();
        return new PageImpl<T>(content, pageable, total);
    }

    @Override
    public Page<T> findAll(Predicate predicate, Pageable pageable, List<Path> projections) {
        Class<T> domainType = getEntityInformation().getJavaType();
        MongodbQuery<T> query = new SpringDataMongodbQuery<T>(mongoOperations, domainType);
        long total = query.count();
        List<T> content = total > pageable.getOffset() ? query.where(predicate).list(projections.toArray(new Path[0])) : Collections.<T>emptyList();
        return new PageImpl<T>(content, pageable, total);
    }
}

自定义存储库工厂

public class CustomQueryDslMongodbRepositoryFactoryBean<R extends QueryDslMongoRepository<T, I>, T, I extends Serializable> extends MongoRepositoryFactoryBean<R, T, I> {


    @Override
    protected RepositoryFactorySupport getFactoryInstance(MongoOperations operations) {
        return new CustomQueryDslMongodbRepositoryFactory<T,I>(operations);
    }

    public static class CustomQueryDslMongodbRepositoryFactory<T, I extends Serializable> extends MongoRepositoryFactory {
        private MongoOperations operations;

        public CustomQueryDslMongodbRepositoryFactory(MongoOperations mongoOperations) {
            super(mongoOperations);
            this.operations = mongoOperations;
        }


        @SuppressWarnings({ "rawtypes", "unchecked" })
        protected Object getTargetRepository(RepositoryMetadata metadata) {
                return new CustomQuerydslMongoRepositoryImpl(getEntityInformation(metadata.getDomainType()), operations);
          }

        protected Class<?> getRepositoryBaseClass(RepositoryMetadata metadata) {
            return CustomQuerydslMongoRepository.class;
        }
    }
}

实体存储库

public interface DocumentRepository extends CustomQuerydslMongoRepository<Document, String>{

}

服务中的使用

@Autowired
DocumentRepository repository;

public List<Document> getAllDocumentsForListing(){
return repository.findAll(  QDocument.document.id.isNotEmpty().and(QDocument.document.version.isNotNull()), new PageRequest(0, 10),QDocument.document.name,QDocument.document.version).getContent();
}
相关问题