我的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
}
}
答案 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
字段和约定的新实例id
将id
转换为_id
。
public class CommentEntity {
private String id;
private LocalDateTime datePosted;
private String comment;
private int likes;
....
public CommentEntity() {
id = new ObjectId().toString();
...
}
}