I am new to Spring Data Mongo, so I have to do something wrong, because I cannot fulfill such a simple request. This is my model:
@Document(collection="brands")
public class Brand{
@Id
private int id;
private String name;
...
}
@Document(collection="models")
public class Model{
@Id
private int id;
private String name;
@DBRef
private Brand brand;
...
}
I would like to get all the models from the brand, so I implement the DAO as follows:
@Repository
public interface IModelDAO extends MongoRepository<Model, Integer>{
@Query(value="{ 'brand.$id' : ?0 }")
public List<Model> findByBrandId(Integer id);
}
If I execute this mongodb request in the shell, it works: db.modelss.find({ 'brand.$id' : 1 })
But a Java application raises the following exception:
Caused by: java.lang.IllegalAccessError
at org.springframework.data.mapping.PropertyReferenceException.detectPotentialMatches(PropertyReferenceException.java:134)
It seems to be looking for the $ id field in the Brand class, and since it does not exist, it fails. Therefore, I change the request to the following, so that it goes into the id field:
@Query(value="{ 'brand.id' : ?0 }")
Now it does not throw an exception, but finds nothing in the database.
Debugging the MongoTemplate.executeFindMultiInternal () method can see that in
DBCursor cursor = null;
try {
cursor = collectionCallback.doInCollection(getAndPrepareCollection(getDb(), collectionName));
query={ "brand" : 134}
. , . = { "brand. $Id": 134} .
, ?