How can I substitute @PrePersist in Spring data r2dbc

2.1k views Asked by At

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?

2

There are 2 answers

0
fyrkov On BEST ANSWER

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

1
Kayaman On

From the docs

Spring Data R2DBC aims at being conceptually easy. In order to achieve this it does NOT offer caching, lazy loading, write behind or many other features of ORM frameworks. This makes Spring Data R2DBC a simple, limited, opinionated object mapper.

So you'll have to either write your own such mechanisms or write persistence code that doesn't depend on them.