【发布时间】:2020-04-27 06:39:15
【问题描述】:
我希望使用 UUID id 和 createdAt / updatedAt 字段存储文档。我的解决方案是使用 Spring Boot 2.1.x。在我从 Spring Boot 2.1.11.RELEASE 升级到 2.2.0.RELEASE 之后,我对 MongoAuditing 的测试以createdAt = null 失败。我需要做什么才能再次填充 createdAt 字段?
这不仅仅是一个测试问题。我运行了该应用程序,它的行为与我的测试相同。所有审计字段都保持为空。
我有一个启用 MongoAuditing 和 UUID 生成的配置:
@Configuration
@EnableMongoAuditing
public class MongoConfiguration {
@Bean
public GenerateUUIDListener generateUUIDListener() {
return new GenerateUUIDListener();
}
}
监听器连接到onBeforeConvert - 我猜这就是麻烦开始的地方。
public class GenerateUUIDListener extends AbstractMongoEventListener<IdentifiableEntity> {
@Override
public void onBeforeConvert(BeforeConvertEvent<IdentifiableEntity> event) {
IdentifiableEntity entity = event.getSource();
if (entity.isNew()) {
entity.setId(UUID.randomUUID());
}
}
}
文档本身(我删除了 getter 和 setter):
@Document
public class MyDocument extends InsertableEntity {
private String name;
}
public abstract class InsertableEntity extends IdentifiableEntity {
@CreatedDate
@JsonIgnore
private Instant createdAt;
}
public abstract class IdentifiableEntity implements Persistable<UUID> {
@Id
private UUID id;
@JsonIgnore
public boolean isNew() {
return getId() == null;
}
}
可以在此处找到完整的最小示例(包括测试)https://github.com/mab/auditable 使用 2.1.11.RELEASE 测试成功,使用 2.2.0.RELEASE 失败。
【问题讨论】:
-
BeforeConvertEvent的执行顺序似乎发生了变化。在 2.2.0 中,首先设置 id,然后isNew无法检查是否需要设置createdAt。
标签: java spring mongodb spring-boot spring-data-mongodb