Spring Data MongoDB BeforeSaveCallback不起作用

我希望具有与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。有人提示吗?

yangguiping007 回答:Spring Data MongoDB BeforeSaveCallback不起作用

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

@Component
public class TestCallBackImpl implements BeforeConvertCallback<Measurement> {

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

}
本文链接:https://www.f2er.com/3070792.html

大家都在问