I'm using Spring-Data for MongoDB:
Version information - org.mongodb.mongo-java-driver version 2.10.1, org.springframework.data.spring-data-mongodb version 1.2.1.RELEASE.
I have a case that's similar to the one defined in here, which is (sorry for the formatting...):
I just started developing some app in Java with spring-data-mongodb and came across some issue that I haven't been able to solve:
I have a couple of document beans like this:
@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 ...
}
And I have a repository class with a method that simply invokes a find similar to this:
public List<? extends Bar> findByFooField(final String fieldValue) {
Query query = Query.query(Criteria.where("foo.someField").is(fieldValue));
return getMongoOperations().find(query, BarImpl.class);
}
Saving a Bar works just fine, it would save it in mongo along with the "_class" attribute for both Foo and Bar. However, finding by some attribute in Foo would throw an exception like this:
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)
The solution that was given was to use the @TypeAlias annotation on the abstract class, which told the framework to use a specific implementation (in this case FooImpl).
In my case, I have interface members, instead of abstract members:
@Document(collection="myBeanBar")
public class BarImpl implements Bar {
String id;
IFoo foo;
// More fields and methods ...
}
I'm very reluctant to put an annotation on the interface IFoo that will give a default implementation, instead I'd like to tell the framework what this field's default implementation in the context of the implementing BarImpl class, similar to @JsonTypeInfo:
@Document(collection="myBeanBar")
public class BarImpl implements Bar {
String id;
@JsonTypeInfo(use = Id.CLASS, defaultImpl = FooImpl.class)
IFoo foo;
// More fields and methods ...
}
I found this answer, which more or less says to avoid using interfaces. but I'd be happy to know if there's no better option.
Any ideas?
Thanks!