use of org.springframework.data.mongodb.core.mapping.event.BeforeSaveCallback in project spring-data-mongodb by spring-projects.
the class MongoTemplateUnitTests method beforeSaveCallbackAllowsTargetDocumentModifications.
// DATAMONGO-2261
@Test
void beforeSaveCallbackAllowsTargetDocumentModifications() {
BeforeSaveCallback<Person> beforeSaveCallback = new BeforeSaveCallback<Person>() {
@Override
public Person onBeforeSave(Person entity, Document document, String collection) {
document.append("added-by", "callback");
return entity;
}
};
StaticApplicationContext ctx = new StaticApplicationContext();
ctx.registerBean(BeforeSaveCallback.class, () -> beforeSaveCallback);
ctx.refresh();
template.setApplicationContext(ctx);
Person entity = new Person();
entity.id = "luke-skywalker";
entity.firstname = "luke";
template.save(entity);
ArgumentCaptor<Document> captor = ArgumentCaptor.forClass(Document.class);
verify(collection).replaceOne(any(), captor.capture(), any(ReplaceOptions.class));
assertThat(captor.getValue()).containsEntry("added-by", "callback");
}
use of org.springframework.data.mongodb.core.mapping.event.BeforeSaveCallback in project spring-data-mongodb by spring-projects.
the class MongoTemplateUnitTests method publishesEventsAndEntityCallbacksInOrder.
// DATAMONGO-2261
@Test
void publishesEventsAndEntityCallbacksInOrder() {
BeforeConvertCallback<Person> beforeConvertCallback = new BeforeConvertCallback<Person>() {
@Override
public Person onBeforeConvert(Person entity, String collection) {
assertThat(entity.id).isEqualTo("before-convert-event");
entity.id = "before-convert-callback";
return entity;
}
};
BeforeSaveCallback<Person> beforeSaveCallback = new BeforeSaveCallback<Person>() {
@Override
public Person onBeforeSave(Person entity, Document document, String collection) {
assertThat(entity.id).isEqualTo("before-save-event");
entity.id = "before-save-callback";
return entity;
}
};
AbstractMongoEventListener<Person> eventListener = new AbstractMongoEventListener<Person>() {
@Override
public void onBeforeConvert(BeforeConvertEvent<Person> event) {
assertThat(event.getSource().id).isEqualTo("init");
event.getSource().id = "before-convert-event";
}
@Override
public void onBeforeSave(BeforeSaveEvent<Person> event) {
assertThat(event.getSource().id).isEqualTo("before-convert-callback");
event.getSource().id = "before-save-event";
}
};
StaticApplicationContext ctx = new StaticApplicationContext();
ctx.registerBean(ApplicationListener.class, () -> eventListener);
ctx.registerBean(BeforeConvertCallback.class, () -> beforeConvertCallback);
ctx.registerBean(BeforeSaveCallback.class, () -> beforeSaveCallback);
ctx.refresh();
template.setApplicationContext(ctx);
Person entity = new Person();
entity.id = "init";
entity.firstname = "luke";
Person saved = template.save(entity);
assertThat(saved.id).isEqualTo("before-save-callback");
}
Aggregations