use of org.springframework.data.mongodb.core.mapping.event.BeforeSaveEvent in project spring-data-mongodb by spring-projects.
the class DefaultBulkOperations method maybeEmitBeforeSaveEvent.
private void maybeEmitBeforeSaveEvent(SourceAwareWriteModelHolder holder) {
if (holder.getModel() instanceof InsertOneModel) {
Document target = ((InsertOneModel<Document>) holder.getModel()).getDocument();
maybeEmitEvent(new BeforeSaveEvent<>(holder.getSource(), target, collectionName));
} else if (holder.getModel() instanceof ReplaceOneModel) {
Document target = ((ReplaceOneModel<Document>) holder.getModel()).getReplacement();
maybeEmitEvent(new BeforeSaveEvent<>(holder.getSource(), target, collectionName));
}
}
use of org.springframework.data.mongodb.core.mapping.event.BeforeSaveEvent 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