java - 如何在从 Mongo 读取而不是读取 DBObject 时转换为 Model 对象?

标签 java mongodb crud

我想知道如何从 MongoDB 读取 saced 对象。

我只是用键(dataStatus)保存它,并且对象已转换为 JSON。

当我尝试检索它时 - 我有 DBObject 而不是我的模型。

简单main():

public static void main(String[] args) {      
        LowFareSearchRQDao searchRQDao = new LowFareSearchRQDao();
        searchRQDao.connect();
        System.out.println(ToStringBuilder.reflectionToString(searchRQDao.read(DataStatus.SUCCESS_LOW_FARE_SEARCH_REQUEST), ToStringStyle.MULTI_LINE_STYLE));
        searchRQDao.disconnect();
    }

输出:

com.mongodb.BasicDBObject@76e134e6[
  _isPartialObject=false
  accessOrder=false
  threshold=12
  loadFactor=0.75
]

这是我的 create():

@Override
public void create(MODEL model) {
    try {
        Field keyField1 = getKeyField(model);
        String fieldValue = getKeyFieldValue(keyField1, model);
        BasicDBObject query = createQuery(keyField1.getName(), fieldValue);

        DBCursor cursor = dbCollection.find(query);
        if (!cursor.hasNext()) {
            DBObject dbObject = getDbObject(model);
            dbCollection.insert(dbObject);
        } else {
            throw new RuntimeException(String.format("Duplicate data status %s with value %s", keyField1.getName(), fieldValue));
        }
    } catch (IOException e) {
        e.printStackTrace();
    }
}

private Field getKeyField(MODEL model) {
    Field keyField = null;
    for (Field field : model.getClass().getDeclaredFields()) {
        if (field.isAnnotationPresent(KeyField.class)) {
            keyField = field;
        }
    }
    if (keyField == null) {
        throw new RuntimeException(String.format("Couldn't find KeyField annotation at class '%s'", model.getClass().getName()));
    }
    return keyField;
}

private String getKeyFieldValue(Field keyField, Object model) {
    String result = null;
    try {
        if(keyField.isAnnotationPresent(KeyField.class)) {
            keyField.setAccessible(true);
            result = keyField.get(model).toString();
        }
        if(result == null || result.equals("")) {
            throw new NullPointerException();
        }
    } catch(NullPointerException e) {
        throw new RuntimeException("KeyField property is empty");
    }catch (Exception e) {
        throw new RuntimeException(String.format("Couldn't find KeyField annotation at class '%s'", model.getClass().getName()));
    }
    return result;
}

private BasicDBObject createQuery(String key, String value) {
    BasicDBObject query = new BasicDBObject();
    query.put(key, value);
    return query;
}

@Override
@SuppressWarnings("unchecked")
public MODEL read(ID id) {
    Field keyField2 = getKeyField(model);
    BasicDBObject query = createQuery(keyField2.getName(), id.toString());

    DBCursor cursor = dbCollection.find(query);
    if (!cursor.hasNext()) {
        throw new RuntimeException(String.format("This id %s isn't presented at collection %s", id.toString(), dbCollection.getFullName()));
    }
    return (MODEL) JSON.parse(String.valueOf(cursor.next()));
}

如何从 DBObject 转换为模型对象?

最佳答案

How to convert from DBObject to your model object?

这是一种可以以简化的方式实现它的方法:

使用参数化构造函数使您的类扩展 BasicDBObject

class Model extends BasicDBObject
{
   public Model(DBObject object) {
        super(object.toMap());
   }
}

在模型中设置值。

Model model = new Model();
model.put("key","value");

将模型插入数据库。

dbCollection.insert(model);

从数据库中检索模型。

while(cursor.hasNext()){
 DbObject obj = cursor.next();
 Model model = new Model(obj);
 //do something with the Model
 }

关于java - 如何在从 Mongo 读取而不是读取 DBObject 时转换为 Model 对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26122332/

相关文章:

java - 让我的 Spring 测试切片扫描单个类而不是整个包

java - 听/通知 pgconnection 关闭 java?

java - 选择更新跳过锁定行限制

ruby-on-rails - 在 Rails Controller 中进一步操作的最佳实践

ruby - Rails 4 嵌套表单 link_to 编辑不在循环中工作

java - 面向对象范式中的方法可以被继承类中具有相同签名的方法覆盖。但是变量不能。为什么?

php - 变更集 Doctrine 事件监听器中的嵌入式文档

java - Spring MongoRepository#findall : ConverterNotFoundException

linux - .NET Core 的 MongoDB C# 驱动程序中不受支持的位置运算符的解决方法

mongodb - MongoDB 中的 replaceOne() 和 updateOne() 有什么区别?