DATAMONGO-771 - Fix raw JSON string handling in MongoTemplate.insert(…).

We now support insertion of JSON objects as plain strings via MongoTemplate.insert(…).

Original pull request: #79.
This commit is contained in:
Thomas Darimont
2013-10-08 10:56:41 +02:00
committed by Oliver Gierke
parent 24e06cf219
commit f0f12d5296
2 changed files with 41 additions and 14 deletions

View File

@@ -700,10 +700,9 @@ public class MongoTemplate implements MongoOperations, ApplicationContextAware {
initializeVersionProperty(objectToSave);
BasicDBObject dbDoc = new BasicDBObject();
maybeEmitEvent(new BeforeConvertEvent<T>(objectToSave));
writer.write(objectToSave, dbDoc);
DBObject dbDoc = toDbObject(objectToSave, writer);
maybeEmitEvent(new BeforeSaveEvent<T>(objectToSave, dbDoc));
Object id = insertDBObject(collectionName, dbDoc, objectToSave.getClass());
@@ -712,6 +711,26 @@ public class MongoTemplate implements MongoOperations, ApplicationContextAware {
maybeEmitEvent(new AfterSaveEvent<T>(objectToSave, dbDoc));
}
/**
* @param objectToSave
* @param writer
* @return
*/
private <T> DBObject toDbObject(T objectToSave, MongoWriter<T> writer) {
if (!(objectToSave instanceof String)) {
DBObject dbDoc = new BasicDBObject();
writer.write(objectToSave, dbDoc);
return dbDoc;
} else {
try {
return (DBObject) JSON.parse((String) objectToSave);
} catch (JSONParseException e) {
throw new MappingException("Could not parse given String to save into a JSON document!", e);
}
}
}
private void initializeVersionProperty(Object entity) {
MongoPersistentEntity<?> mongoPersistentEntity = getPersistentEntity(entity.getClass());
@@ -851,19 +870,9 @@ public class MongoTemplate implements MongoOperations, ApplicationContextAware {
assertUpdateableIdIfNotSet(objectToSave);
DBObject dbDoc = new BasicDBObject();
maybeEmitEvent(new BeforeConvertEvent<T>(objectToSave));
if (!(objectToSave instanceof String)) {
writer.write(objectToSave, dbDoc);
} else {
try {
dbDoc = (DBObject) JSON.parse((String) objectToSave);
} catch (JSONParseException e) {
throw new MappingException("Could not parse given String to save into a JSON document!", e);
}
}
DBObject dbDoc = toDbObject(objectToSave, writer);
maybeEmitEvent(new BeforeSaveEvent<T>(objectToSave, dbDoc));
Object id = saveDBObject(collectionName, dbDoc, objectToSave.getClass());

View File

@@ -1996,6 +1996,24 @@ public class MongoTemplateTests {
assertThat(result.get(2).getClass(), is((Object) VerySpecialDoc.class));
}
/**
* @see DATAMONGO-771
*/
@Test
public void allowInsertWithPlainJsonString() {
String id = "4711";
String value = "bubu";
String json = String.format("{_id:%s, field: '%s'}", id, value);
template.insert(json, "sample");
List<Sample> result = template.findAll(Sample.class);
assertThat(result.size(), is(1));
assertThat(result.get(0).id, is(id));
assertThat(result.get(0).field, is(value));
}
static interface Model {
String value();