首页 > 解决方案 > 无法从中获取标识符

问题描述

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;

 .....
}

标签: javamongodbspring-data

解决方案


对于任何正在努力解决这个问题的人 - 就我而言,这是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在您保存新实体时使用这些字段!


推荐阅读