我的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
}
}还有相应的实体类
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 MongoTemplate作为插入。当注释插入到MongoTemplate文档中时,如何配置_id自动生成注释,如下所示
{
"_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
}
}发布于 2020-02-16 20:56:03
Spring数据将类映射到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();
...
}
}https://stackoverflow.com/questions/60246374
复制相似问题