Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating a complex query using QueryDSL and MongoDB in Java

I have set up MongoDB following this tutorial

http://www.littlelostmanuals.com/2011/09/spring-mongodb-type-safe-queries.html

Everything works as expected but now I'm stuck at a point where I want to be able to query on multiple fields.

Currently I have repository interfaces for each type I'm saving and can search on a single field fine.

public interface StartedEventRepository extends 
    MongoRepository<DatablockStartedEvent, String>,
    QueryDslPredicateExecutor<DatablockStartedEvent> { 

}

Below is the query for a single parameter.

        return startedEventRepo
            .findOne(QDatablockStartedEvent.datablockStartedEvent.searchId
                    .eq(searchId));

Is it possible to create a Query object where I can say something similar to the following.

if(someName != null){
    query.where(QMyClass.name.eq(someName));
}
if(someTime != null){
    query.where(QMyClass.time.eq(someTime));
}

List result = query.list();

I've tried looking at the MongodbQuery but I couldn't get it to work. Any ideas?

I saw an example http://www.mkyong.com/mongodb/spring-data-mongodb-update-document/ but this uses the mongoTemplate. Is there no way to achieve this through the repositories and if not, are they useless?

like image 879
DeliveryNinja Avatar asked Jul 03 '26 12:07

DeliveryNinja


2 Answers

It should be possible. Something like this maybe

BooleanBuilder builder = new BooleanBuilder();

if(someName != null){
    builder.and(QMyClass.name.eq(someName));
}
if(someTime != null){
    builder.and(QMyClass.time.eq(someTime));
}

repository.findAll(builder.getValue())
like image 123
Timo Westkämper Avatar answered Jul 06 '26 00:07

Timo Westkämper


Without ever working with Spring Data, I would guess from Reading this http://static.springsource.org/spring-data/data-document/docs/1.0.0.M2/reference/html/#mongodb.repositories.queries that you simply declare a method in your repository where the Method name tells your query structure (this guess is supported through example 4.3 on the same site). Not sure If you can generate dynamic Queries, this was the only one a quick search revealed.

like image 23
philnate Avatar answered Jul 06 '26 00:07

philnate



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!