Spring 数据 MongoDB BeforeSaveCallback 不工作

Spring Data MongoDB BeforeSaveCallback not working

我想拥有与 JPA @PrePersist 类似的功能,但在 mongodb 数据库中。阅读 spring 数据 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。有人有任何提示吗?

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

@Component
public class TestCallBackImpl implements BeforeConvertCallback<Measurement> {

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

}