【问题标题】:Spring Data MongoDB BeforeSaveCallback not workingSpring Data MongoDB BeforeSaveCallback 不起作用
【发布时间】:2020-03-15 09:50:23
【问题描述】:

我希望拥有与 JPA @PrePersist 类似的功能,但在 mongodb 数据库中。阅读 spring data mongodb 文档,我发现了实体回调:https://docs.spring.io/spring-data/mongodb/docs/current/reference/html/#entity-callbacks。它们似乎可以满足我的需要,因此我正在尝试实现一些回调。我知道我正在做的事情有一些替代方案(审核注释),但我想暂时保留这一点。

这是我注册回调、我的实体定义和存储库的方式:

@Configuration
public class BeforeSaveCallbackConfiguration {

    @Bean
    BeforeSaveCallback<Measurement> beforeSaveMeasurement() {
        return (entity, document, collection) -> {
            entity.setTimestamp(System.currentTimeMillis());
            System.out.println("Before save, timestamp: " + entity.getTimestamp());
            return entity;
        };
    }
}

public interface MeasurementRepository extends MongoRepository<Measurement, String> {
}

@Document
public class Measurement {

    private String id;
    private long timestamp;
    private Float value1;
    private Float value2;
    // constructor, getters, setters ...
}

我使用存储库的measurementRepository.save 方法保存实体。我实际上看到了带有时间戳的回调的打印行。但是,保存在 mongodb 集合中的数据始终将时间戳设置为 0。有人有任何提示吗?

【问题讨论】:

    标签: spring mongodb spring-data-mongodb


    【解决方案1】:

    你实现BeforeConvertCallback接口可以为你工作:

    @Component
    public class TestCallBackImpl implements BeforeConvertCallback<Measurement> {
    
        @Override
        public Measurement onBeforeConvert(Measurement entity, String collection) {
            entity.setTimestamp(System.currentTimeMillis());
            return entity;
        }
    
    }
    

    【讨论】:

    • 我注册了一个 BeforeConvertCallback 而不是 BeforeSaveCallback。它现在正在工作,非常感谢。但是我仍然不知道它们之间的区别以及为什么不使用 before save 回调。
    • 我在测试中发现beforeSaveCallback并没有改变实体信息,在我看来它的作用只是在持久化之前获取实体信息,详细说明可以查看this网址。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-06-25
    • 1970-01-01
    • 2020-07-27
    • 1970-01-01
    相关资源
    最近更新 更多