18

MongoDB 似乎返回 BSON/JSON 对象。

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

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

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

我的方法如下所示:

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;
    }

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

4

5 回答 5

46

让 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/

于 2013-06-13T08:54:16.403 回答
8

有一些 Java 库可以帮助您:

于 2011-10-07T07:34:35.330 回答
6

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

我使用 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);

}
于 2014-01-06T03:20:15.863 回答
5

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 帖子中查看我对 org.bson.Document 和 Vice Versa的回答

于 2018-04-19T16:45:03.027 回答
3

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

于 2011-12-28T04:38:04.990 回答