春天数据MongoDB BeforeSaveCallback不工作。

问题描述 投票:0回答:1

我想拥有类似于JPA的功能。@PrePersist 但在mongodb数据库中。在阅读spring data mongodb文档时,我发现了实体回调。https:/docs.spring.iospring-datamongodbdocscurrentreferencehtml#实体回调。. 它们似乎可以满足我的需求,所以我正在尝试实现一些回调。我知道对于我正在做的事情有一些替代方案(审计注释),但我想暂时用这个。

这就是我如何注册回调,我的实体定义和存储库。

@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。然而,保存在mongodb集合中的数据总是将时间戳设置为0,有人有什么提示吗?

spring mongodb spring-data-mongodb
1个回答
1
投票

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

@Component
public class TestCallBackImpl implements BeforeConvertCallback<Measurement> {

    @Override
    public Measurement onBeforeConvert(Measurement entity, String collection) {
        entity.setTimestamp(System.currentTimeMillis());
        return entity;
    }

}
© www.soinside.com 2019 - 2024. All rights reserved.