如何在Spring Data R2DBC中替代使用 @PrePersist?

huangapple go评论72阅读模式
英文:

How can I substitute @PrePersist in Spring data r2dbc

问题

我在Spring Webflux应用程序中使用了 spring-boot-starter-data-r2dbc 模块(版本1.1.3)。\我希望在持久化层中添加实体生命周期回调。\使用Spring Data JPA,可以通过诸如 @PrePersist@PreUpdate 等注解来实现这一点。\是否有一种方便的方式可以在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?

答案1

得分: 5

spring-data-r2dbc:1.2.0开始,它是新的Spring Data 2020.0版本的一部分,新的“生命周期实体回调API”使得这种操作成为可能。

以下是一个简短的示例:

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) {
        // 进行一些操作
        return Mono.just(entity);
    }
}

以下是一些文档:
https://docs.spring.io/spring-data/r2dbc/docs/current/reference/html/#r2dbc.entity-callbacks

英文:

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&lt;MyEntity&gt; {

    @Override
    public Publisher&lt;MyEntity&gt; 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

答案2

得分: 0

来自文档

Spring Data R2DBC的目标是在概念上保持简单。为了实现这一点,它不提供缓存、惰性加载、写入背后或许多其他ORM框架的功能。这使得Spring Data R2DBC成为一个简单、有限、有观点的对象映射器。

因此,您将不得不编写自己的这些机制,或者编写不依赖于它们的持久化代码。

英文:

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.

huangapple
  • 本文由 发表于 2020年9月30日 02:50:00
  • 转载请务必保留本文链接:https://go.coder-hub.com/64125839.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定