Reputation: 827
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?
Upvotes: 2
Views: 9004
Reputation: 22200
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())
Upvotes: 10
Reputation: 1506
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.
Upvotes: 1