So, what solutions do you have if you are in the Java land wanting to use MongoDB?
- using the MongoDB Java driver API
- GuiceyData: ProtocolBuffers-like mapping
- Sculptor: DSL for code generation
- Morphia: JPA-like API
- GuiceyData vs Morphia vs Sculptor
Using MongoDB Java driver API
Lets start with a code snippet to get a feeling of the MongoDB Java driver:
Another good resource are the following slides from Brendan W. McAdams:
If using the Java driver feels too verbose, then I have some Groovy sugar for it.
MongoDB driver API with Groovy sugar
Same James Williams has ☞ a post on the how things can get a bit better when using Groovy and MongoDB.
GuiceyData: ProtocolBuffers-like mapping
In ☞ this post, Matt Insler talks about the complexity of using schemaless NoSQL databases and statically types languages.
One of the best things about MongoDB is the lack of an enforced schema for collections. […] All of that being said, working with these records in a language like Java and on large diverse teams of people who don’t want to open the database and inspect the records to see what values and sub-records are available, means that you will always spend time wrapping these records in a strong-typed class. Wrapping up loose data into classes that can both access and create that data sounds just like another project I’ve used recently.
and he comes out with a possible solution based on external data definitions:
The GuiceyData Generator is a quick and easy way to specify strongly typed data structures to be stored in a MongoDB database and mapped to wrappers and builders in Java.
As a side note, BSON is a typed serialization format, so the real problem is just type mapping.
Sculptor: DSL for code generation
Another code generator, based on an internal DSL is ☞ Sculptor.
Sculptor generates data mapper classes that converts domain objects to/from MongoDB data structures, DBObjects. This makes it easy to use a domain model à la DDD with automatic mapping to MongoDB data structures.
Sculptor provides generic repository operations for use with MongoDB. This includes operations such as save, delete, findById, findByKey, findByCondition, and some more. You get CRUD operations, and GUI, for free.
A different approach is proposed by ☞ Morphia which feels closer to JPA.
According to the slidedeck below:
- brings Hibernate/JPA paradigms to MongoDB
- allows annotating of POJOs to make converting them between MongoDB and Java very easy
- supports DAO abstractions
- offers type-safe query support
- compatible with GWT, Guice, Spring, and DI frameworks
A look at Morphia performance and possible optimizations can be found ☞ here.
GuiceyData vs Morphia vs Sculptor
If you have a hard time deciding which one should you pick, you’ll probably find ☞ this article resource useful.
With that I guess you should just get started. And if you have a preferred approach to using MongoDB in Java please share it with the rest of us!