top of page
Search
  • Writer's pictureYumeng Liu

Convert POJO to/from BSON

Background:


POJO stands for Plain Old Java Objects. It denoted a Java object which does not follow any of the major Java object models, conventions, or frameworks (wikipedia).


BSON is the binary encoding of JSON-like documents that MongoDB uses when storing documents in collections (source).


Problem Definition:


While I am using Spring Boot framework to connect to MongoDb instance, I need to serialize the POJO to BSON, and deserialize from BSON to POJO. As legacy ways, users need to write explicit classes to connect the two foreign lands. We are searching for a more practical, comprehensive and intelligent way to do such boilerplate codes.


Solutions:

CodecRegistry pojoCodecRegistry = fromRegistries(
    MongoClientSettings.getDefaultCodecRegistry(),
    fromProviders(
        PojoCodecProvider.builder().automatic(true).build()
    )
);

We can create a custom CodecRegistry and provide it when we connect to the MongoDb instance. It will provide the out-of-box experience to translate POJO to/from BSON. Based on the documentation, it will work on most useful Java non-premitive data types including String, Integer, Double..., upon which your own object classes are built.


Side Notes:

  • Some data types (e.g. UUID) may need extra Codec configurations. Their configurations should be provided above getDefaultCodecRegistry.

CodecRegistry pojoCodecRegistry = fromRegistries(
    fromCodecs(new UuidCodec(UuidRepresentation.STANDARD)),
    // and any other configurations...
    MongoClientSettings.getDefaultCodecRegistry(),
    fromProviders(
        PojoCodecProvider.builder().automatic(true).build()
    )
);
  • By default the PojoCodec will search for the default empty public constructor in the POJO. It also relies on the public setters and getters. The default behavior may limit the design styles of your POJO. E.g. No final fields.



25 views0 comments

Recent Posts

See All

Be Lazy in Java

Laziness may not be a good thing in daily life, but could be a useful strategy in software development. Let's take a look at the following codes. Are there any differences between the two functions? T

Java Optional

NullPointerException can be annoying in Java, and the designer even regretted inventing it, calling it as "my billion-dollar mistake". Luckily Optional class was introduced in Java 8, making it an inc

Journey with React, Spring Boot and Google Cloud

Several months ago I started my journey with Spring Boot and React. Local development is a pleasure, thanks to the great framework, convenient tools and friendly environment. I created the Spring boot

Post: Blog2_Post
bottom of page