我刚接触Spring Data Mongo,可能做错了什么,因为我无法执行这样一个简单的查询。这是我的数据模型:
@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
}
我想获取某个品牌的所有型号,因此我按照以下方式实施DAO:
@Repository
public interface IModelDAO extends MongoRepository<Model, Integer>{
@Query(value="{ 'brand.$id' : ?0 }")
public List<Model> findByBrandId(Integer id);
}
如果我在Shell中执行此mongodb查询,它可以正常工作:db.modelss.find({ 'brand.$id' : 1 })
但是,在Java应用程序中会抛出以下异常:
Caused by: java.lang.IllegalAccessError
at org.springframework.data.mapping.PropertyReferenceException.detectPotentialMatches(PropertyReferenceException.java:134)
显然它正在Brand类中寻找一个名为 $id 的字段,由于该字段不存在,因此导致失败。因此,我将查询更改为以下内容,以便导航到 id 字段:
@Query(value="{ 'brand.id' : ?0 }")
现在它不会抛出异常,但它在数据库中没有找到任何内容。在调试MongoTemplate.executeFindMultiInternal()方法时,可以看到:
DBCursor cursor = null;
try {
cursor = collectionCallback.doInCollection(getAndPrepareCollection(getDb(), collectionName));
游标的查询是 query={ "brand" : 134}
。因此,它找不到任何内容是有道理的。在调试过程中将查询值更改为 query={ "brand.$id" : 134},就可以工作了。
那么,为什么查询没有正确翻译?
{"user.$id":{"$oid":"123456789012345678901234"}}
。 - Amnon