使用 Spring MongoTemplate 自动生成数组中 MongoDB 子文档的 ID

Mee*_*ary 4 java mongodb spring-data spring-data-mongodb spring-boot

我的 MongoDB 文档结构post是这样的

{
"_id" : ObjectId("5e487ce64787a51f073d0915"),
"active" : true,
"datePosted" : ISODate("2020-02-15T23:21:10.329Z"),
"likes" : 400,
"commentList" : [ 
    {
        "datePosted" : ISODate("2020-02-15T23:21:10.329Z"),
        "comment" : "I read all your posts and always think they don't make any sense",
        "likes" : 368
    }, 
    {
        "datePosted" : ISODate("2020-02-15T23:21:10.329Z"),
        "comment" : "I enjoy all your posts and are great way to kill time",
        "likes" : 3533
    }
}
Run Code Online (Sandbox Code Playgroud)

并且有对应的实体类

CommentEntity.java

public class CommentEntity{

  private String id;
  private LocalDateTime datePosted;
  private String comment;
  private int likes;

  ....

}
Run Code Online (Sandbox Code Playgroud)

PostEntity.java

@Document(collection = "post")
public class PostEntity {

  @Id
  private String id;
  private boolean active;
  private LocalDateTime datePosted;
  private int likes;
  private List<CommentEntity> commentList;

  ....

}
Run Code Online (Sandbox Code Playgroud)

我正在使用 Spring DataMongoTemplate进行插入。如何配置为在将注释插入文档时MongoTemplate自动生成注释,如下所示_idpost

{
"_id" : ObjectId("5e487ce64787a51f073d0915"),
"active" : true,
"datePosted" : ISODate("2020-02-15T23:21:10.329Z"),
"likes" : 400,
"commentList" : [ 
    {
        "_id" : ObjectId("5e487ce64787a51f07snd315"),
        "datePosted" : ISODate("2020-02-15T23:21:10.329Z"),
        "comment" : "I read all your posts and always think they don't make any sense",
        "likes" : 368
    }, 
    {
        "_id" : ObjectId("5e48764787a51f07snd5j4hb4k"),
        "datePosted" : ISODate("2020-02-15T23:21:10.329Z"),
        "comment" : "I enjoy all your posts and are great way to kill time",
        "likes" : 3533
    }
}
Run Code Online (Sandbox Code Playgroud)

Val*_*jon 7

Spring Data将您的类映射到 MongoDB 文档。映射时,只能_id自动生成。

MongoDB 要求所有文档都有一个“_id”字段。如果您不提供,驱动程序将使用生成的值分配一个 ObjectId。用注释的字段@Id (org.springframework.data.annotation.Id)将映射到“_id”字段。

没有注释但已命名的字段id将映射到该_id字段。

https://docs.spring.io/spring-data/mongodb/docs/current/reference/html/#mapping.conventions.id-field

解决方法:

字段和约定ObjectId的新实例将转换为.idid_id

public class CommentEntity {

    private String id;
    private LocalDateTime datePosted;
    private String comment;
    private int likes;

    ....

    public CommentEntity() {
        id = new ObjectId().toString();
        ...
    }

}
Run Code Online (Sandbox Code Playgroud)