Since MongoDB uses BSON, a binary form of JSON, to store its documents, a JSON mapper is a perfect mechanism for mapping Java objects to MongoDB documents. And the best Java JSON mapper is Jackson. Jackson’s parsing/generating interface fits serialising to MongoDBs documents like a glove. Its plugins, custom creators, serialisers, views, pluggable annotators and so on give this mapping library a massive head start, making it powerful, performant, and robust.
This is what using MongoJack looks like:
JacksonDBCollection<MyObject, String> coll = JacksonDBCollection.wrap(dbCollection, MyObject.class, String.class); MyObject myObject = ... WriteResult<MyObject, String> result = coll.insert(myObject); String id = result.getSavedId(); MyObject savedObject = coll.findOneById(id);
Both the object itself and the id of the object are strongly typed. If the id is generated, you can easily obtain it from the write result.
@javax.persistance.Idannotation for marking which property is the id (or just call it