Reputation: 581
I have a Java application that retrieves data from mongo DB using Spring data . I have a case where i wanted to retrive all Objects from mongo collection where isDeleted flag is set to false .
I tried to use org.springframework.data.domain.ExampleMatcher as explained in https://github.com/spring-projects/spring-data-examples/tree/master/mongodb/query-by-example ,but it didn't work(returns 0 records) . Below is code snippet of my attempt.
NOTE: I tried both by adding and removing withIgnoreNullValues() in below snippet .It did not help .
public List<Adns> getAll(){
Adns matcherObject = new Adns();
matcherObject.setDeleted(false);
ExampleMatcher matcher = ExampleMatcher.matching().withIgnoreNullValues().
withMatcher("isDeleted", exact());
Example<Adns> example = Example.of(matcherObject,matcher);
return adnsRepository.findAll(example);
}
I am able to retrieve all the object without that boolean filter successfully . Below is the working code .
public List<Adns> getAll(){
return adnsRepository.findAll();
}
Upvotes: 4
Views: 14073
Reputation: 11
Be careful when using example matchers if your Probe object (in this case Adns) has primitive types such as boolean.
There is no way of instantiating that object with such properties unset. This is because primitives always take a default value (false for booleans) and cannot be assigned to null. So, any search by example using that probe might end up with an undesired side effect if your intention is to search by any other field: the primitive field will always be included (with its default 'false' value) in the example.
Now, regarding your question, I suggest you to print out the json representation of your probe object (use jackson's modelmapper to do so) to detect any field taking a default value (such as empty strings insted of null values). Besides that, your field is called deleted in the model so the proper matcher should be:
withMatcher("deleted", exact());
Anyway it's always better to use the findBy.... methods in the repository and rely on the spring-data-mongodb automatic implementation hope it helped.
Upvotes: 0
Reputation: 6326
You need to create the method declaration findByDeletedIsFalse
on your repository interface.
At runtime, spring data will find this interface and create an implementation for it automatically. This is in fact one of the key features of spring-data. You can read more about query methods in the docs. The spring docs are very easy to read and full of examples.
Assuming your Adns
uses a Long
as primary ID, and that you are using the basic CrudRepository
provider you should have:
public interface AdnsRepository extends CrudRepository<Adns, Long> {
// this method declaration is automatically implemented by the spring-data library at runtime.
List<Adns> findByDeletedIsFalse();
}
More information about query method generation:
Upvotes: 1