Spring Data Mongo - how to request field identifier @DBRef

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;
    ...
    //getters-setters
}

@Document(collection="models")
public class Model{
    @Id
    private int id;
    private String name;
    @DBRef
    private Brand brand;
    ...
    //getters-setters
}

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} .

, ?

+4
2

@Id int. Integer :

@Document(collection="brands")
public class Brand{
    @Id
    private Integer id;

    private String name;
    ...
    //getters-setters
}

@Document(collection="models")
public class Model{
    @Id
    private Integer id;
    private String name;
    @DBRef
    private Brand brand;
    ...
    //getters-setters
}
+4

;

Query que = new Query();
que.addCriteria(Criteria.where("user.$id").is(new ObjectId("123456789012345678901234")));
0

Source: https://habr.com/ru/post/1612220/


All Articles