【问题标题】:Convert DBObject to a POJO using MongoDB Java Driver使用 MongoDB Java 驱动程序将 DBObject 转换为 POJO
【发布时间】:2019-02-11 17:47:19
【问题描述】:

MongoDB 似乎返回 BSON/JSON 对象。

我认为您肯定能够以字符串、整数等形式检索值,然后可以将其保存为 POJO。

由于迭代列表 ... (cur.next()),我有一个 DBObject(实例化为 BasicDBObject)。

是使用 JSON 序列化器/反序列化器将数据导入 POJO 的唯一方法(除了使用某种持久性框架之外)吗?

我的方法是这样的:

public List<User> findByEmail(String email){
         DBCollection userColl;
         try {
            userColl = Dao.getDB().getCollection("users"); } catch (UnknownHostException e) { e.printStackTrace(); } catch (MongoException e) { e.printStackTrace();}
            DBCursor cur = userColl.find();
            List<User> usersWithMatchEmail = new ArrayList<User>();

            while(cur.hasNext()) {
               // this is where I want to convert cur.next() into a <User> POJO
               usersWithMatchEmail.add(cur.next());
            }
        return null;
    }

编辑:这很明显,只要做这样的事情。

【问题讨论】:

  • 愚蠢的我,您可以在 DBObject 上调用 get() 并获取值。我会发布代码。
  • 我只想指出最新的答案,其中提出了驱动程序原生解决方案:stackoverflow.com/a/49926224/503900

标签: java mongodb dbobject


【解决方案1】:

让 Spring 用它已经为此构建的东西来完成繁重的工作......

真正的诀窍是:mongoTemplate.getConverter().read(Foo.class, obj);

例如,当使用 DBCursor -

while (cursor.hasNext()) { 
    DBObject obj = cursor.next(); 
    Foo foo = mongoTemplate.getConverter().read(Foo.class, obj);  
    returnList.add(foo); 
}

http://revelfire.com/spring-data-mongodb-convert-from-raw-query-dbobject/

【讨论】:

  • 非常感谢您。快速入门,maven 依赖是:org.springframework.data / spring-data-mongodb / 1.3.2.RELEASE
  • 你应该得到一个 cookie :D
  • 干得好克里斯马蒂亚斯。但我也需要扭转这个过程。即将java对象转换为BasicDbObject。有什么帮助吗?谢谢
  • 问题不在于 SPRING
【解决方案2】:

有一些 java 库可以帮助您:

【讨论】:

  • 谢谢,现在我正在尝试学习 Java API,但最终会使用其中之一。
  • +1 for spring-data-mongodb,太棒了。具有指定文档 ID、字段名称、文档引用的注释;请注意不支持级联保存:static.springsource.org/spring-data/data-mongodb/docs/current/…
  • @AndrewB 可以在 EJB 项目中使用 Spring 数据 mongodb 吗?这是明智的做法吗?因为我的项目的其余部分对 Spring 没有任何依赖!
【解决方案3】:

虽然回答晚了,但有人可能会觉得这很有用。

我使用 GSON 将 BasicDBObject 转换为我自己的 POJO,即 TinyBlogDBObject

TinyBlogDBObject obj = convertJSONToPojo(cursor.next().toString());

private static TinyBlogDBObject convertJSONToPojo(String json){

    Type type = new TypeToken< TinyBlogDBObject >(){}.getType();

    return new Gson().fromJson(json, type);

}

【讨论】:

  • 这不起作用,因为以 {"_id":{"$oid":xxxx} 形式返回的 id 并且 gson 抱怨。您需要手动将其转换为字符串或替换 jsonobject 中的值。
  • 或者您可以首先将自己的 _id 值作为字符串提供,并避免出现此类问题。
【解决方案4】:

1.为 MongoDatabase bean 提供适当的 CodecRegistry

@Bean
public MongoClient mongoClient() {
    ConnectionString connectionString = new ConnectionString("mongodb://username:password@127.0.0.1:27017/dbname");

    ConnectionPoolSettings connectionPoolSettings = ConnectionPoolSettings.builder()
            .minSize(2)
            .maxSize(20)
            .maxWaitQueueSize(100)
            .maxConnectionIdleTime(60, TimeUnit.SECONDS)
            .maxConnectionLifeTime(300, TimeUnit.SECONDS)
            .build();

    SocketSettings socketSettings = SocketSettings.builder()
            .connectTimeout(5, TimeUnit.SECONDS)
            .readTimeout(5, TimeUnit.SECONDS)
            .build();

    MongoClientSettings clientSettings = MongoClientSettings.builder()
            .applyConnectionString(connectionString)
            .applyToConnectionPoolSettings(builder -> builder.applySettings(connectionPoolSettings))
            .applyToSocketSettings(builder -> builder.applySettings(socketSettings))
            .build();

    return MongoClients.create(clientSettings);
}

@Bean 
public MongoDatabase mongoDatabase(MongoClient mongoClient) {
    CodecRegistry defaultCodecRegistry = MongoClientSettings.getDefaultCodecRegistry();
    CodecRegistry fromProvider = CodecRegistries.fromProviders(PojoCodecProvider.builder().automatic(true).build());
    CodecRegistry pojoCodecRegistry = CodecRegistries.fromRegistries(defaultCodecRegistry, fromProvider);
    return mongoClient.getDatabase("dbname").withCodecRegistry(pojoCodecRegistry);
}

2。注释 POJOS

public class ProductEntity {

    @BsonProperty("name") public final String name;
    @BsonProperty("description") public final String description;
    @BsonProperty("thumb") public final ThumbEntity thumbEntity;

    @BsonCreator
    public ProductEntity(
            @BsonProperty("name") String name,
            @BsonProperty("description") String description,
            @BsonProperty("thumb") ThumbEntity thumbEntity) {
        this.name = name;
        this.description = description;
        this.thumbEntity = thumbEntity;
    }
}

public class ThumbEntity {

    @BsonProperty("width") public final Integer width;
    @BsonProperty("height") public final Integer height;
    @BsonProperty("url") public final String url;

    @BsonCreator
    public ThumbEntity(
            @BsonProperty("width") Integer width,
            @BsonProperty("height") Integer height,
            @BsonProperty("url") String url) {
        this.width = width;
        this.height = height;
        this.url = url;
    }
}

3.查询mongoDB获取POJOS

MongoCollection<Document> collection = mongoDatabase.getCollection("product");
Document query = new Document();
List<ProductEntity> products = collection.find(query, ProductEntity.class).into(new ArrayList<>());

请查看我在其他帖子中的回答
POJO to org.bson.Document and Vice Versa

【讨论】:

  • 在使用 POJO 的情况下如何处理日期/时间类?
  • 您根本不必使用日期/时间 mongo 数据类型。相反,您可以使用 long 数据类型来保存当前时间戳。还有第二个可能更好的选择,您可以从 ObjectId 获取日期。我总是使用这两个选项之一(long 或 object id),我从不使用日期/时间 mongo 数据类型
【解决方案5】:

您可以使用谷歌提供的GSON 库。这是它的example。您可以使用许多其他 api 将 json 转换为 pojo,例如 jettision api 等。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-10-26
    • 1970-01-01
    相关资源
    最近更新 更多