我正在使用Spring-Data来操作MongoDB:
版本信息 - org.mongodb.mongo-java-driver版本为2.10.1,org.springframework.data.spring-data-mongodb版本为1.2.1.RELEASE。
我有一个类似于这里定义的情况(抱歉格式有点乱...):
我刚开始使用Java和spring-data-mongodb开发某个应用程序时遇到了一些问题,但我一直没有解决:
我有几个文档bean,如下所示:
@Document(collection="myBeanBar")
public class BarImpl implements Bar {
String id;
Foo foo;
// More fields and methods ...
}
@Document
public class FooImpl implements Foo {
String id;
String someField;
// some more fields and methods ...
}
我有一个仓库类,其中有一个方法只是简单地调用了类似于这样的查找方法:
public List<? extends Bar> findByFooField(final String fieldValue) {
Query query = Query.query(Criteria.where("foo.someField").is(fieldValue));
return getMongoOperations().find(query, BarImpl.class);
}
保存 Bar 对象没有问题,它会将其存储在 mongo 中,并且会为 Foo 和 Bar 都添加 "_class" 属性。然而,通过 Foo 的某个属性查找时会抛出如下异常:
Exception in thread "main" java.lang.IllegalArgumentException: No
property someField found on test.Foo!
at org.springframework.data.mapping.context.AbstractMappingContext.getPersistentPropertyPath(AbstractMappingContext.java:225)
at org.springframework.data.mongodb.core.convert.QueryMapper.getPath(QueryMapper.java:202)
at org.springframework.data.mongodb.core.convert.QueryMapper.getTargetProperty(QueryMapper.java:190)
at org.springframework.data.mongodb.core.convert.QueryMapper.getMappedObject(QueryMapper.java:86)
at org.springframework.data.mongodb.core.MongoTemplate.doFind(MongoTemplate.java:1336)
at org.springframework.data.mongodb.core.MongoTemplate.doFind(MongoTemplate.java:1322)
at org.springframework.data.mongodb.core.MongoTemplate.find(MongoTemplate.java:495)
at org.springframework.data.mongodb.core.MongoTemplate.find(MongoTemplate.java:486)
给出的解决方案是在抽象类上使用@TypeAlias注释,这告诉框架使用特定的实现(在这种情况下为FooImpl)。
在我的情况下,我有接口成员而不是抽象成员:
@Document(collection="myBeanBar")
public class BarImpl implements Bar {
String id;
IFoo foo;
// More fields and methods ...
}
我非常不愿意在接口IFoo上放置一个注释,以提供默认实现。相反,我想告诉框架,在实现BarImpl类的上下文中,这个字段的默认实现是什么,类似于@JsonTypeInfo:
@Document(collection="myBeanBar")
public class BarImpl implements Bar {
String id;
@JsonTypeInfo(use = Id.CLASS, defaultImpl = FooImpl.class)
IFoo foo;
// More fields and methods ...
}
我找到了这个答案,它或多或少地说要避免使用接口。但如果没有更好的选择,我很乐意知道。
有什么想法吗?
谢谢!
org.springframework.data
?这样你就可以看到生成的查询并将其与你的MongoDB模式进行比较。 - Patouche