DATAMONGO-588 - Version attribute now gets initialized on insert.

The version attribute of an entity has not been correctly initialized to 0 when inserting objects using MongoTemplate.insert(…). We now set it to 0 correctly.
This commit is contained in:
Oliver Gierke
2012-12-10 17:38:16 +09:00
parent 42df25434f
commit 42ab4cb7b4
2 changed files with 42 additions and 0 deletions

View File

@@ -657,6 +657,8 @@ public class MongoTemplate implements MongoOperations, ApplicationContextAware {
assertUpdateableIdIfNotSet(objectToSave);
initializeVersionProperty(objectToSave);
BasicDBObject dbDoc = new BasicDBObject();
maybeEmitEvent(new BeforeConvertEvent<T>(objectToSave));
@@ -669,6 +671,16 @@ public class MongoTemplate implements MongoOperations, ApplicationContextAware {
maybeEmitEvent(new AfterSaveEvent<T>(objectToSave, dbDoc));
}
private void initializeVersionProperty(Object entity) {
MongoPersistentEntity<?> mongoPersistentEntity = getPersistentEntity(entity.getClass());
if (mongoPersistentEntity == null || mongoPersistentEntity.hasVersionProperty()) {
BeanWrapper<PersistentEntity<Object, ?>, Object> wrapper = BeanWrapper.create(entity, null);
wrapper.setProperty(mongoPersistentEntity.getVersionProperty(), 0);
}
}
public void insert(Collection<? extends Object> batchToSave, Class<?> entityClass) {
doInsertBatch(determineCollectionName(entityClass), batchToSave, this.mongoConverter);
}
@@ -713,6 +725,8 @@ public class MongoTemplate implements MongoOperations, ApplicationContextAware {
List<DBObject> dbObjectList = new ArrayList<DBObject>();
for (T o : batchToSave) {
initializeVersionProperty(o);
BasicDBObject dbDoc = new BasicDBObject();
maybeEmitEvent(new BeforeConvertEvent<T>(o));

View File

@@ -1422,6 +1422,34 @@ public class MongoTemplateTests {
template.save("Foobar!", "collection");
}
/**
* @see DATAMONGO-588
*/
@Test
public void initializesVersionOnInsert() {
PersonWithVersionPropertyOfTypeInteger person = new PersonWithVersionPropertyOfTypeInteger();
person.firstName = "Dave";
template.insert(person);
assertThat(person.version, is(0));
}
/**
* @see DATAMONGO-588
*/
@Test
public void initializesVersionOnBatchInsert() {
PersonWithVersionPropertyOfTypeInteger person = new PersonWithVersionPropertyOfTypeInteger();
person.firstName = "Dave";
template.insertAll(Arrays.asList(person));
assertThat(person.version, is(0));
}
static class MyId {
String first;