Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring data mongodb repository findAll field exclusion

I have a strange issue for the spring data mongodb repositories.. I want to exclude a field from my findAll request. How can I achieve this ?

This works perfectly:

@Query(fields = "{'objectContentAsJson':0}")
Page<ObjectHistory> findByObjectIdAndServiceIgnoreCase( String objectId, String service, Pageable pageable );

But no chance for findAll:

@Query(fields = "{'objectContentAsJson':0}")
Page<ObjectHistory> findAll( Pageable pageable );

This throws:

Caused by: org.springframework.data.mapping.PropertyReferenceException: No property findAll found for type ObjectHistory! at org.springframework.data.mapping.PropertyPath.(PropertyPath.java:75) at org.springframework.data.mapping.PropertyPath.create(PropertyPath.java:327) at org.springframework.data.mapping.PropertyPath.create(PropertyPath.java:307) at org.springframework.data.mapping.PropertyPath.from(PropertyPath.java:270) at org.springframework.data.mapping.PropertyPath.from(PropertyPath.java:241) at org.springframework.data.repository.query.parser.Part.(Part.java:76)

like image 981
Sercan Ozdemir Avatar asked Feb 11 '16 08:02

Sercan Ozdemir


People also ask

Why does spring boot with MongoDB findAll () return empty array?

The issue arises because the collection name is not explicitly given in your model class, so spring-data derives the collection name from the class name ( Courses ) into camel case ( courses ). Since your actual collection is called Courses , no results are found.

What is the difference between MongoOperations and MongoTemplate?

MongoTemplate provides a simple way for you to save, update, and delete your domain objects and map those objects to documents stored in MongoDB. You can save, update and delete the object as shown below. MongoOperations is the interface that MongoTemplate implements.

Which is better MongoTemplate or MongoRepository?

MongoTemplate is a bit more lower level where you need to write your own queries. With embedded documents and denormalization it can be easier to write complex queries with MongoTemplate. For simple things I would use MongoRepository. I've seen some examples where both are used together in a hybrid approach.


1 Answers

Adding an empty filter criteria will do the trick for you:

@Query(value = "{}", fields = "{'objectContentAsJson':0}")
Page<ObjectHistory> findAll(Pageable pageable);

Apparently, when you do not specify the value parameter to filter results, Spring Data tries to derive a query from the method name and somehow, does not recognize the special meaning of findAll.

like image 50
Ali Dehghani Avatar answered Sep 22 '22 13:09

Ali Dehghani