java - 无法从中获取标识符
问题描述
MongoDB
尝试将实体保存到数据库时出现以下问题。
我在用Spring
CrudRepository
我的代码如下所示:
UserDocument user = processUser();
userRepository.save(user);
这是我得到的错误:
java.lang.IllegalStateException: Could not obtain identifier from UserDocument(id=null, ownerId=..., ...)!
at o.s.d.m.TargetAwareIdentifierAccessor.getRequiredIdentifier(TargetAwareIdentifierAccessor.java:47)
at o.s.d.m.c.EntityOperations$MappedEntity.getId(EntityOperations.java:466)
... 53 frames excluded
用户文档类:
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.NoArgsConstructor;
import lombok.experimental.Accessors;
import lombok.experimental.SuperBuilder;
import org.bson.types.ObjectId;
import org.springframework.data.annotation.Id;
import org.springframework.data.mongodb.core.index.CompoundIndex;
import org.springframework.data.mongodb.core.index.CompoundIndexes;
import org.springframework.data.mongodb.core.mapping.Document;
@Data
@EqualsAndHashCode(callSuper = true)
@NoArgsConstructor
@AllArgsConstructor
@Accessors(chain = true)
@SuperBuilder
@Document(collection = UserDocument.COLLECTION)
public class UserDocument extends BaseDocument<ObjectId> {
public static final String COLLECTION = "users";
@Id
private ObjectId id;
.....
}
解决方案
对于任何正在努力解决这个问题的人 - 就我而言,这是mapstruct
Mapper
一个问题,因为副作用是填充超类中的字段:
import org.springframework.data.annotation.CreatedDate;
import org.springframework.data.annotation.LastModifiedDate;
import org.springframework.data.annotation.Version;
@Data
@NoArgsConstructor(access = AccessLevel.PROTECTED)
@AllArgsConstructor(access = AccessLevel.PROTECTED)
@Accessors(chain = true)
@SuperBuilder
public abstract class BaseDocument<ID extends Serializable> implements Persistable<ID> {
@Version
private Long revision;
@CreatedDate
private Instant createdDateTime;
@LastModifiedDate
private Instant lastModifiedDateTime;
@Override
public boolean isNew() {
return isNull(createdDateTime);
}
}
因此,请确保null
在您保存新实体时使用这些字段!
推荐阅读
- php - php 7.3 - 类常量作为默认参数值崩溃
- html - 如何确保可折叠表格后面的文本显示在其下方,而不是右侧?
- javascript - 使用 javascript 打开页面时立即显示上传对话框
- python - 我有一个包含文本和计算的 excel 文件,在 python 中读取 excel 文件的最佳方法是什么?
- firebase - 在 Firebase 控制台中创建主题
- java - 编写方法的顺序是否重要?
- javascript - 如何在 p5js 中预加载pose Net?
- regex - 在 SAS 中使用 PRX 语法实现负向回溯
- php - 未找到 Laravel 控制器 5.7
- django - 测试权限被拒绝未捕获