VGuna and I (johannz) discussed this on September 9 in http://forum.springsource.org/showth...9-returns-null
I created a bug for it: https://jira.springsource.org/browse/DATADOC-275 - DBRef fields and collections are returning nulls. In that bug I researched the cause, and have a proposed fix.
Copied from the bug:
Analysis
I think the problem is in the MappingMongoConverter, and how it is storing DBRefs. Looking at the code for the createDBRef method, it is not doing any type conversion of the ID that it retrieves from the target object, when it should be.
From the createDBRef method, exception handling removed:
Code:
Object id = null;
BeanWrapper<MongoPersistentEntity<Object>, Object> wrapper = BeanWrapper.create(target, conversionService);
id = wrapper.getProperty(idProperty, Object.class, useFieldAccessOnly);
String collection = dbref.collection();
if ("".equals(collection)) {
collection = targetEntity.getCollection();
}
String dbname = dbref.db();
DB db = StringUtils.hasText(dbname) ? mongoDbFactory.getDb(dbname) : mongoDbFactory.getDb();
return new DBRef(db, collection, id);
Suggested fix
I suspect the line "id = wrapper.getProperty(idProperty, Object.class, useFieldAccessOnly);" should be replaced by this code, copied from writeInternal:
Code:
Object idObj = null;
Class<?>[] targetClasses = new Class<?>[] { ObjectId.class, String.class, Object.class };
for (Class<?> targetClass : targetClasses) {
try {
idObj = wrapper.getProperty(idProperty, targetClass, useFieldAccessOnly);
if (null != idObj) {
break;
}
} catch (ConversionException ignored) {
} catch (IllegalAccessException e) {
throw new MappingException(e.getMessage(), e);
} catch (InvocationTargetException e) {
throw new MappingException(e.getMessage(), e);
}
}
if (null != idObj) {
dbo.put("_id", idObj);
} else {
if (!VALID_ID_TYPES.contains(idProperty.getType())) {
throw new MappingException("Invalid data type " + idProperty.getType().getName()
+ " for Id property. Should be one of " + VALID_ID_TYPES);
}
}