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

时间:2020-02-16 07:35:02

标签: java mongodb spring-boot spring-data spring-data-mongodb

我的post的MongoDB文档结构如下

{
"_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
    }
}

还有相应的实体类

CommentEntity.java

public class CommentEntity{

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

  ....

}

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;

  ....

}

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

{
"_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
    }
}

1 个答案:

答案 0 :(得分:2)

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();
        ...
    }

}