Wednesday, 28 August 2019

springboot mongo lifecycle events



https://github.com/spring-projects/spring-data-mongodb/blob/8340c02d9a13fd42d898dcdc5a6b822cddf73f40/src/main/asciidoc/reference/mongodb.adoc#lifecycle-events


https://www.baeldung.com/cascading-with-dbref-and-lifecycle-events-in-spring-data-mongodb


You will see online(the 2nd link above) that this feature is used for cascade(for Dbref), but this can be used for Root obj, not only for DBref.



it has multi functions, you just


@Configuration
public class Config {
    
@Bean
MongoTransactionManager transactionManager(MongoDbFactory dbFactory) {
return new MongoTransactionManager(dbFactory);
}
@Bean
public MyMongoEventListener getMyListener() {
    return new MyMongoEventListener();
}

}
class MyMongoEventListener extends AbstractMongoEventListener<Object> {

    @Override
    public void onAfterSave(AfterSaveEvent<Object> event) {
    Object source = event.getSource(); 
        if (source instanceof YourType) { 
        System.out.println(source);
        }
    }
    
    @Override
    public void onBeforeSave(BeforeSaveEvent<Object> event) {
    Object source = event.getSource(); 
        if (source instanceof YourType) { 
        System.out.println(source);
        }
    }

    @Override
    public void onAfterLoad(AfterLoadEvent<Object> event) {
    
    }
}



Note: this doesn't work with other program , which means, if you use shell  or compass or robo to change data (delete, create)  your java program will not get it.


https://github.com/spring-projects/spring-data-mongodb/blob/8340c02d9a13fd42d898dcdc5a6b822cddf73f40/src/main/asciidoc/reference/mongodb.adoc

1 comment: