如果createdBy引用具有唯一索引的文档,则无法抛出 dup key 错误。
AbstractDocument.java
public abstract class AbstractDocument implements Auditable<User, String> {
@Version
private Long version;
@Id
private String id;
private User createdBy;
private DateTime createdDate;
private User lastModifiedBy;
private DateTime lastModifiedDate;
}
User.java
@Document(collection = "users")
public class User extends AbstractDocument {
private String name;
private String surname;
@Indexed(unique = true)
private String username;
}
Book.java
@Document(collection = "books")
public Book extends AbstractDocument {
private String title;
}
现在,我有一个脚本(Spring Batch),它用一些书来初始化数据库。该脚本以这种方式定义审计员:
@Configuration
@EnableMongoAuditing
public class MongoConfig {
@Bean
public AuditorAware<User> auditorProvider() {
return new AuditorAware<User>() {
@Override
public User getCurrentAuditor() {
User auditor = new User();
auditor.setUsername("init-batch");
auditor.setName("Data initializer");
auditor.setSurname("Data initializer");
return auditor;
}
};
}
}
某处的剧本(对于我需要保留的每本书) bookRepository.save(书)
第一本书是坚持的,但第二本书却抛出:
嵌套异常是com.mongodb.DuplicateKeyException:写入失败,错误代码为11000,错误消息为“E11000重复键错误索引:mydb.books。$ createdBy.username dup key:{:”init-batch“} '
为什么呢?唯一索引是用户集合,为什么要检查审计引用?