gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 18:24:36 26 4
gpt4 key购买 nike

我的 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 在将注释插入 post 文档时自动生成 _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
}
}

最佳答案

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

MongoDB requires that you have an '_id' field for all documents. If you don't provide one the driver will assign a ObjectId with a generated value. A field annotated with @Id (org.springframework.data.annotation.Id) will be mapped to the '_id' field.

A field without an annotation but named id will be mapped to the _id field.

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

解决方法:

id 字段和约定实例新的 ObjectId 会将 id 转换为 _id

public class CommentEntity {

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

....

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

}

关于java - 使用 Spring MongoTemplate 自动生成数组中 MongoDB 子文档的 ID,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60246374/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com