gpt4 book ai didi

java - 在Spring Boot java项目中如何将不同数据类型的属性从mongo DB映射到java类?

转载 作者:行者123 更新时间:2023-12-02 10:50:55 42 4
gpt4 key购买 nike

嗨,我有一个 mongo DB 文档部分,其列属性如图所示(第一种格式)

   "columns" : [
[
{
"itemId" : ObjectId("5b863b50083ae5eb1e678d75"),
"type" : "field"
}
],
[
{
"itemId" : ObjectId("5b8d4404af0963f54e262f46"),
"type" : "field"
}
],
[

],
[

]
]


which is of the type Array of Array of Objects

However at some places it is also stored in this format as well . (2nd format)


"columns" : [
{
"0" : {
"itemId" : "5b863b50083ae5eb1e678d75",
"type" : "field"
}
},
{
"0" : {
"itemId" : "5b8d4404af0963f54e262f46",
"type" : "field"
}
},
{

},
{

}
]

作为对象的对象数组

现在我有 dao 类 someObject 来存储最内部的对象

public class SomeObject{

private ObjectId itemId;
private String type;
public ObjectId getItemId() {
return itemId;
}
public void setItemId(ObjectId itemId) {
this.itemId = itemId;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}

}

这里是Dao类部分

public class Section{

private List<List<SomeObject>> columns;

public List<List<someObject>> getColumns() {
return columns;
}

public void setColumns(List<List<SomeObject>> columns) {
this.columns = columns;
}
}

节类如何适用于第一种格式,因为我将类型设置为列表

但是第二种格式会中断,因为它有不同

我也尝试过使用这个类

Public class Section {

private List<Object> columns;

}

这映射了第二种格式,但破坏了第一种格式我收到以下错误

 "exceptionDetails": "Cannot convert [Document{{itemId=5877f2345449aef957e1d8ec, type=field}}] of type class java.util.ArrayList into an instance of class java.lang.Object! Implement a custom Converter<class java.util.ArrayList, class java.lang.Object> and register it with the CustomConversions.

请有人建议我如何通过 dao 类创建,以便它可以映射这两种格式?我需要实现自定义映射器吗?如果是的话怎么办?

最佳答案

我觉得你有点不明白什么是DAO类(class)。你拥有的是JavaBeans .

关于你的问题,正如你注意到的以及异常详细信息中报告的那样,你的文档是一个 ArrayList ,为什么不将其读取为 ArrayList 然后设置它到 Section 字段?但如果这个选项不适合您,您可以实现 Custom Converter ,这也会在异常详细信息中报告给您。

关于java - 在Spring Boot java项目中如何将不同数据类型的属性从mongo DB映射到java类?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52198461/

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