DATAMONGO-551 - MongoTemplate can now persist plain Strings if they are valid JSON.
Added some code to MongoTemplate that inspects the object to be saved for being a String. If it is we try to parse the given String into a JSON document and continue as if we had been given a DBObject initially. Non-parseable Strings are rejected with a MappingException.
This commit is contained in:
@@ -101,6 +101,7 @@ import com.mongodb.ReadPreference;
|
||||
import com.mongodb.WriteConcern;
|
||||
import com.mongodb.WriteResult;
|
||||
import com.mongodb.util.JSON;
|
||||
import com.mongodb.util.JSONParseException;
|
||||
|
||||
/**
|
||||
* Primary implementation of {@link MongoOperations}.
|
||||
@@ -790,6 +791,7 @@ public class MongoTemplate implements MongoOperations, ApplicationContextAware {
|
||||
}
|
||||
}
|
||||
|
||||
@SuppressWarnings("unchecked")
|
||||
protected <T> void doSave(String collectionName, T objectToSave, MongoWriter<T> writer) {
|
||||
|
||||
assertUpdateableIdIfNotSet(objectToSave);
|
||||
@@ -797,7 +799,16 @@ public class MongoTemplate implements MongoOperations, ApplicationContextAware {
|
||||
DBObject dbDoc = new BasicDBObject();
|
||||
|
||||
maybeEmitEvent(new BeforeConvertEvent<T>(objectToSave));
|
||||
writer.write(objectToSave, dbDoc);
|
||||
|
||||
if (!(objectToSave instanceof String)) {
|
||||
writer.write(objectToSave, dbDoc);
|
||||
} else {
|
||||
try {
|
||||
objectToSave = (T) JSON.parse((String) objectToSave);
|
||||
} catch (JSONParseException e) {
|
||||
throw new MappingException("Could not parse given String to save into a JSON document!", e);
|
||||
}
|
||||
}
|
||||
|
||||
maybeEmitEvent(new BeforeSaveEvent<T>(objectToSave, dbDoc));
|
||||
Object id = saveDBObject(collectionName, dbDoc, objectToSave.getClass());
|
||||
|
||||
@@ -1393,6 +1393,22 @@ public class MongoTemplateTests {
|
||||
assertThat(result.get("_id"), is(dbObject.get("_id")));
|
||||
}
|
||||
|
||||
/**
|
||||
* @see DATAMONGO-551
|
||||
*/
|
||||
@Test
|
||||
public void writesPlainString() {
|
||||
template.save("{ 'foo' : 'bar' }", "collection");
|
||||
}
|
||||
|
||||
/**
|
||||
* @see DATAMONGO-551
|
||||
*/
|
||||
@Test(expected = MappingException.class)
|
||||
public void rejectsNonJsonStringForSave() {
|
||||
template.save("Foobar!", "collection");
|
||||
}
|
||||
|
||||
static class MyId {
|
||||
|
||||
String first;
|
||||
|
||||
Reference in New Issue
Block a user