springboot项目中操作mongodb对Document进行插入操作,对其数组字段对象中的元素使用自动填充
@Data
@Document
public class TestDocument {
@MongoId
private String id;
private List<TestField> fields;
}
@Data
public class TestField {
@MongoId
private String id;
private String name;
@CreatedDate
private LocalDateTime time;
}
TestDocument testDocument = new TestDocument();
TestField testField = new TestField();
testField.setName("测试");
testDocument.setFields(Collections.singletonList(testField));
System.out.println(mongoTemplate.save(testDocument));
插入操作返回的数据未能自动填充
{
"_id": "6414466c347e397d7d393b0e",
"fields": [
{
"name": "测试"
}
]
}
Document内嵌List字段中的元素是否能使用自动填充?需要怎么配置内嵌List字段中的元素才能使用自动填充?
参考GPT和自己的思路:
是的,Document内嵌List字段中的元素可以使用自动填充。在上述代码中,TestField对象中使用了@CreatedDate注解,这是一个MongoDB在插入操作时自动填充创建时间的注解。但是在List中的元素要使用这个注解需要一些额外的配置。
修改后的代码如下所示:
@Data
@Document
public class TestDocument {
@MongoId
private String id;
@Field(targetType = TestField.class)
private List<TestField> fields;
}
@Data
@Document(collection = "testdocument.fields")
public class TestField {
@MongoId
private String id;
private String name;
@CreatedDate
private LocalDateTime time;
}
这样配置之后,在进行Document对象插入操作时,内嵌List字段中的元素就会自动填充创建时间了。