Convert DBObject to a POJO using MongoDB Java Driver

[亡魂溺海] 提交于 2019-11-27 14:39:41

问题


MongoDB seems to return BSON/JSON objects.

I thought that surely you'd be able to retrieve values as Strings, ints etc. which can then be saved as POJO.

I have a DBObject (instantiated as a BasicDBObject) as a result of iterating over a list ... (cur.next()).

Is the only way (other than using some sort of persistence framework) to get the data into a POJO to use a JSON serlialiser/deserialiser?

My method looks like this:

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

EDIT: It's pretty obvious, just do something like this.


回答1:


There is a few java libs that can help you with it:

  • Morhpia - http://code.google.com/p/morphia/
  • Spring Data for MongoDB - http://www.springsource.org/spring-data/mongodb



回答2:


Let Spring do the heavy lifting with the stuff it already has built for this...

The real trick is: mongoTemplate.getConverter().read(Foo.class, obj);

For example, when using a 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/




回答3:


Though a late answer , someone might find this useful.

I use GSON to convert from BasicDBObject to my own POJO which is 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);

}



回答4:


1. Provide MongoDatabase bean with proper 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. Annotate 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. Query mongoDB and obtain POJOS

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

Please check my answer in other post
POJO to org.bson.Document and Vice Versa




回答5:


You can use GSON library provided by Google. Here is the example of it. There are many other api that you can use to convert json into pojo like jettision api,etc.



来源:https://stackoverflow.com/questions/7684223/convert-dbobject-to-a-pojo-using-mongodb-java-driver

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!