Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

POJO to org.bson.Document and Vice Versa

Is there a simple way to convert Simple POJO to org.bson.Document?

I'm aware that there are ways to do this like this one:

Document doc = new Document();
doc.append("name", person.getName()):

But does it have a much simpler and typo less way?

like image 778
yesterdaysfoe Avatar asked Sep 04 '16 19:09

yesterdaysfoe


People also ask

How do I convert a document to POJO?

//If you want to use Document MongoCollection<Document> myCollection = db. getCollection("mongoCollection"); Document doc=new Document(); doc. put("name","ABC"); myCollection. insertOne(doc); //If you want to use POJO MongoCollection<Pojo> myCollection = db.

How do you turn a POJO object into a map?

A quick look at how to convert a POJO from/to a Map<K, V> with Jackson: // Create ObjectMapper instance ObjectMapper mapper = new ObjectMapper(); // Converting POJO to Map Map<String, Object> map = mapper. convertValue(foo, new TypeReference<Map<String, Object>>() {}); // Convert Map to POJO Foo anotherFoo = mapper.

What is Morphia MongoDB?

Morphia is a wrapper around the Java driver for MongoDB. It acts as an ODM (Object Document Model) for MongoDB documents. Its original goal was to provide an easy mapping to POJO (Plain Old Java Objects). Nowadays, newer versions of the Java driver support this mapping out of the box.

What is BSON library?

The BSON library comprehensively supports BSON, the data storage and network transfer format that MongoDB uses for “documents”. BSON, short for Binary JSON, is a binary-encoded serialization of JSON-like documents. Documents: Documentation of the driver's support for BSON document representations.


1 Answers

Currently Mongo Java Driver 3.9.1 provide POJO support out of the box
http://mongodb.github.io/mongo-java-driver/3.9/driver/getting-started/quick-start-pojo/
Let's say you have such example collection with one nested object

db.createCollection("product", {
validator: {
    $jsonSchema: {
        bsonType: "object",
        required: ["name", "description", "thumb"],
        properties: {
            name: {
                bsonType: "string",
                description: "product - name - string"
            },
            description: {
                bsonType: "string",
                description: "product - description - string"
            },
            thumb: {
                bsonType: "object",
                required: ["width", "height", "url"],
                properties: {
                    width: {
                        bsonType: "int",
                        description: "product - thumb - width"
                    },
                    height: {
                        bsonType: "int",
                        description: "product - thumb - height"
                    },
                    url: {
                        bsonType: "string",
                        description: "product - thumb - url"
                    }
                }
            }

        }
    }
}});

1. Provide a 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 your 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<>());


And that's it !!! You can easily obtain your POJOS without cumbersome manual mappings and without loosing ability to run native mongo queries

like image 193
kamildab_84 Avatar answered Sep 27 '22 22:09

kamildab_84