简体   繁体   中英

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?

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM