2

I have a Spring Data MongoDB Repository that I want to query with a search criteria defined as an object.

Details:

I have a model class:

@Document
public class ModelClass {

    @Id
    private String id;

    private String field1;
    private String field2;
    ...
    private String field10;

    // getters and setters
}

I also have a MongoRepository to store instances of such class:

public interface Repo extends MongoRepository<ModelClass,String> {}

I would like to query the repository using instances of ModelClass as search criteria.Such instances may not have values in all fields (some fields may hold null). So, in the Repo interface, I need something like:

List<ModelClass> findByXXXX(ModelClass criteria);

The goal is to query the Repo without the need of writing all the possible combinations of fields.

1
  • Well, the spring-data API doesn't have it. The closest thing I can think of is findByField1AndField2...AndField10 and put the fields which are frequent in your queries and are (or should be) indexed at the begining Commented Jan 25, 2014 at 12:09

1 Answer 1

3

For very dynamic queries, Spring Data JPA integrates with Querydsl. It allows you to define predicates on the fly and execute them as MongoDB queries. The reference documentation has details on that.

Sign up to request clarification or add additional context in comments.

1 Comment

Reference documentation link gives a 404, I suppose the corresponding current link is probably docs.spring.io/spring-data/mongodb/docs/current/reference/html/…

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.