Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

QueryDslMongoRepository Projection

I am using spring-data for mongodb with querydsl. I have a repository

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

and an entity

@QueryEntity
public class Document {

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

}

I need to load a list of documents with id and name informations. So only id and name should be loaded and set in my entity. I think query projection is the right word for it. Is this supported?

In addition I need to implement some lazy loading logic. Is there anything like "skip" and "limit" features in a repository?

like image 525
DCO Avatar asked Sep 10 '26 23:09

DCO


1 Answers

There's quite a few aspects to this, as it is - unfortunately - not a single question but multiple ones.

For the projection you can simply use the fields attribute of the @Query annotation:

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

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

You can combine this with the query derivation mechanism (by not setting query), with pagination (see below) and even a dedicated projection type in the return clause (e.g. a DocumentExcerpt with only id and name fields).

Pagination is fully supported on the repository abstraction. You already get findAll(Pageable) and a Querydsl specific version of the method by extending the base interfaces. You can also use the pagination API in finder methods adding a Pageable as parameter and returning a Page

Page<Document> findByDescriptionLike(String description, Pageable pageable)

See more on that in the reference documentation.

like image 132
Oliver Drotbohm Avatar answered Sep 14 '26 01:09

Oliver Drotbohm



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!