The latest journey in my quest to see just how many new technologies and frameworks I can learn in one week involves Morphia. Morphia is a "Java Object Document Mapper for MongoDB". In other words, it let's us map our POJOs and POGOs to MongoDB Documents and persist them in MongoDB. This is normally where I try to insert some clever, contextually appropriate image to lure my readers into thinking I'm both smart and clever and they should read all my blog posts and share them with all their friends, but, when I did a Google search for 'Morphia' I got one of the strangest damn collections of images that I've ever seen. I'll present that to you here without comment and then move on to the nerdery.
Right, so, on to the codes. To get started with Morphia...honestly - it pains me to type that name. No offense, but now that I've been tainted by that Google image search I'm not sure I'll ever be able to type or speak that word without picturing a skin disorder. OK...rant over...I promise. To get started, declare a dependency as such:
compile group: 'org.mongodb.morphia', name: 'morphia', version: '1.3.1'Obviously you'll need to make sure you've got access to a running instance of MongoDB before you try to connect/persist to it. Next, create a domain class - we'll call this one
We've annotated this domain class with
@Entity and the ID with
@Id as required by the framework. To make things a bit more realistic, I've wrapped some common functionality for dealing with a
Person in a
PersonService. The service will handle getting a reference to the framework and the datastore (I'd probably include that in an abstract service in a real application) and has a
findById() method. Standard stuff:
Next we'll create a simple route in Spark Java to interact with our
PersonService, create and persist a new
Person if necessary and return a list of Persons to our view.
And finally, the view code if you're dying to see that:
Which results in the following:
And that's simple object based persistence in MongoDB via a Spark Java application.
To wrap things up, I'm still not sure how I feel about NoSQL solutions like Mongo. They've come a long way, and they're obviously as easy to work with as your standard ORM application, but something about the lack of a solid schema behind the data frightens me. What happens when you need to add properties in the future? What if they need to be non-nullable? What if one of your co-workers who is notorious for typos (not you, Scott, I promise) fat-fingers the name of a property and you want to fix it after it's been in production for 6 months? It's much too risky for me in that regard. It just doesn't feel flexible enough for typical CRUD - but maybe good for other options like audit trails and logging purposes?