Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring data find by "_class " value

We are using spring data mongo repositories to store/retrieve documents. Following is the Java structure of classes we have got: Abstract class A -> Concrete Classes B and C We are writing the documents using save() method. when a document is saved, "_class" variable is saved which stores the classPath. Now, when we try and query the data, we are getting the documents of both B and C classes. Following is the example:

public List<B> findByName (String name);

When we call this method, the list (surprisingly) contains the objects of C as well. It may be because B and C have one property which has same name. My question is, if we want to restrict the result to specific class, is it possible using Mongo repository? We tried with findBy_Class, findByClass but it threw an exception saying it was not able to find "class" member in "B".

Shouldn't the return type (e.g. List<B>) help filtering the objects? Any ideas?

Thanks in advance.

like image 285
Darshan Mehta Avatar asked Aug 16 '26 00:08

Darshan Mehta


1 Answers

On the query object there's a "restrict" method which returns only objects of a given type. http://docs.spring.io/spring-data/mongodb/docs/current/api/index.html?org/springframework/data/mongodb/core/MongoOperations.html I suppose you could do something like that :

query.restrict(B.class).findByName(...)
like image 164
vincent Avatar answered Aug 18 '26 23:08

vincent



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!