【发布时间】: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