'AfterDeleteEvent from AbstractMongoEventListener is not being triggered when entry is deleted from MongoDb
I have a class that extends AbstractMongoEventListener
and overrides onAfterSave
and onAfterDelete
.
The onAfterDelete
does not trigger for some reason. The onAfterSave
works fine.
Is there a different configuration that needs to be done for it?
public class ClassX extends AbstractMongoEventListener<DomainClass> {
@Override
public void onAfterSave(AfterSaveEvent<DomainClass> event) {
//dosomething
}
@Override
public void onAfterDelete(AfterDeleteEvent<DomainClass> event) {
//dosomething
}
}
I have already checked the database and the data is being properly deleted, but the onAfterDelete still don't get called.
Any suggestion of what could be the problem?
The repository:
public interface DomainClassRepository extends MongoRepository<DomainClass, String> {
}
I'm calling the method DomainClassRepository.delete(instanceOfDomainClass)
to delete the entry in the db.
Solution 1:[1]
Short answer:
Mongo events could be triggered with typed queries only.
I've tried spring-data-mongodb-2.2.8
version, it handles DomainClassRepository.delete(instanceOfDomainClass)
and DomainClassRepository.deleteById(idOfDomainClass)
properly.
Method onAfterDelete
can't be triggered when DomainClassRepository.deleteAll()
is called because it's untyped.
Long answer (Research):
Check onApplicationEvent
method in AbstractMongoEventListener
.
It contains this code block:
if (event instanceof AbstractDeleteEvent) {
Class<?> eventDomainType = ((AbstractDeleteEvent) event).getType();
if (eventDomainType != null && domainClass.isAssignableFrom(eventDomainType)) {
if (event instanceof BeforeDeleteEvent) {
onBeforeDelete((BeforeDeleteEvent<E>) event);
}
if (event instanceof AfterDeleteEvent) {
onAfterDelete((AfterDeleteEvent<E>) event);
}
}
return;
}
And check AbstractDeleteEvent
under package org.springframework.data.mongodb.core.mapping.event
. Constructor allows to have nullable type:
/**
* Creates a new {@link AbstractDeleteEvent} for the given {@link Document} and type.
*
* @param document must not be {@literal null}.
* @param type may be {@literal null}.
* @param collectionName must not be {@literal null}.
* @since 1.8
*/
public AbstractDeleteEvent(Document document, @Nullable Class<T> type, String collectionName) {
super(document, document, collectionName);
this.type = type;
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Yuriy Kiselev |