MongoDB is an extremely useful document-based database in NoSQL field. There are various drivers and client libraries in MongoDB Ecosystem and detailed manual to facilitate the developers to get into it shortly. In the beginning, we use MongoDB Java driver to manipulate CRUD operations on databases. Everything is running well but lots of
BasicDBObject cause the code lack of readability and fluency. In addition, we employ POJO classes as intermediates between business logic and databases. However, it also brings many laborious and tedious works for converting POJOs into BasicDBObjects before we want to persist custom objects to the database.
Then we find the Java driver provides a
DBObject interface to save custom objects to the database as long as the POJOs implement this interface:
1 2 3
This approach offers an easy way to convert the document we retrieved to a DBobject instance. Then we can perform some operations (e.g, set values to fields) and save it back easily:
However, is there a better way to do this?
In my opinion, Morphia is a better alternative library for mapping POJOs to/from MongoDB. We can define our entity by Annotations, including the embedded and reference documents within the database. Most of all, Morphia also provides the Data Access Objects (DAO) mechanism to persist the objects. Here’s an excellent introduction to Morphia provided by Jeff Yemin.
The remaining part of this article will note down some usage or discussions of Morphia.
We use MongoClient to create a database connection with internal connection pool instead of deprecated Mongo class. It’s designed with the Singleton pattern, and the properties are defined as resource in order to easy to modify. Then just call the
getMongoClient function to get a MongoClient instance.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30
Serialization and Deserialization ObjectId with Jackson
In order to serve an object in JSON as a RESTful resource, we can turn on the JSON POJO support in
web.xml in Tomcat:
1 2 3 4 5 6 7 8 9 10 11 12 13
However, we will get something like this formation for ObjectId field in returned JSON,
1 2 3 4 5 6 7 8 9
instead of the following style:
Fortunately, Alejandro Ayuso provides a way to solve the Jackson serialization problem for MongoDB’s ObjectId – the
ObjectIdSerializer class and your custom class can set
JsonSerialize property with it:
1 2 3 4 5 6 7 8
With a few code changes for optimisation, Morphia has now made it to within 99.5% of the performance of the base Mongo install.
Morphia provides a fluent and comfortable interface to operate arrays. We can remove one or multi objects from an array field through
1 2 3 4 5 6 7
Moreover, you can pull out more than one object by providing
1 2 3