Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert DBObject to a POJO using MongoDB Java Driver

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.

like image 980
Ankur Avatar asked Oct 07 '11 07:10

Ankur


5 Answers

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/

like image 143
chris mathias Avatar answered Nov 20 '22 08:11

chris mathias


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
like image 26
Igor Artamonov Avatar answered Nov 20 '22 08:11

Igor Artamonov


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

}
like image 21
Tito Avatar answered Nov 20 '22 10:11

Tito


1. Provide MongoDatabase bean with proper CodecRegistry

@Bean
public MongoClient mongoClient() {
    ConnectionString connectionString = new ConnectionString("mongodb://username:[email protected]: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

like image 5
kamildab_84 Avatar answered Nov 20 '22 09:11

kamildab_84


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.

like image 2
Anand Soni Avatar answered Nov 20 '22 10:11

Anand Soni