Search code examples
javaspring-dataspring-webfluxproject-reactorspring-data-r2dbc

How can I substitute @PrePersist in Spring data r2dbc


I am using spring-boot-starter-data-r2dbc (version 1.1.3) module in Spring Webflux application.
I want to add entity lifecycle callbacks to my persistence layer.
With Spring Data JPA it was possible with annotations like @PrePersist, @PreUpdate, etc.
Is there any convenient way to achieve this with Spring Data r2dbc?


Solution

  • Starting from the spring-data-r2dbc:1.2.0 which is a part of the new Spring Data 2020.0 release it is possible with the new "Lifecycle Entity Callback API".

    Here is a short example:

    import org.springframework.data.r2dbc.mapping.event.BeforeSaveCallback;
    
    
    @Component
    public class DefaultingEntityCallback implements BeforeSaveCallback<MyEntity> {
    
        @Override
        public Publisher<MyEntity> onBeforeSave(final MyEntity entity,
                                                final OutboundRow row,
                                                final SqlIdentifier table) {
            // do something
            return Mono.just(entity);
        }
    }
    

    Here is some documentation: https://docs.spring.io/spring-data/r2dbc/docs/current/reference/html/#r2dbc.entity-callbacks