cod*_*ent 9 java spring mongodb spring-data spring-data-mongodb
我是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
}
Run Code Online (Sandbox Code Playgroud)
我想从一个品牌获得所有模型,所以我实现DAO如下:
@Repository
public interface IModelDAO extends MongoRepository<Model, Integer>{
@Query(value="{ 'brand.$id' : ?0 }")
public List<Model> findByBrandId(Integer id);
}
Run Code Online (Sandbox Code Playgroud)
如果我在shell中执行这个mongodb查询,它可以工作: db.modelss.find({ 'brand.$id' : 1 })
但是,Java应用程序抛出以下异常:
Caused by: java.lang.IllegalAccessError
at org.springframework.data.mapping.PropertyReferenceException.detectPotentialMatches(PropertyReferenceException.java:134)
Run Code Online (Sandbox Code Playgroud)
显然它正在寻找Brand类中的字段$ id,因为它不存在,所以它失败了.所以我将查询更改为以下内容,以便导航到id字段:
@Query(value="{ 'brand.id' : ?0 }")
Run Code Online (Sandbox Code Playgroud)
现在,它不会抛出异常,但它在DB中找不到任何内容.
调试MongoTemplate.executeFindMultiInternal()方法可以看到它
DBCursor cursor = null;
try {
cursor = collectionCallback.doInCollection(getAndPrepareCollection(getDb(), collectionName));
Run Code Online (Sandbox Code Playgroud)
cursor的查询是query={ "brand" : 134}
.所以它没有找到任何东西是有道理的.在调试期间将查询值更改为query = {"brand.$ id":134}它可以正常工作.
那么,为什么查询没有正确翻译?
问题是由@Id
int类型引起的.将其更改为整数解决了它:
@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
}
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
15947 次 |
最近记录: |