recursive.codes


The Personal Blog of Todd Sharp

MongoDB via Morphia in Spark Java

Posted By: Todd Sharp on 4/7/2017 2:05 GMT
Tagged: Groovy, Java, MongoDB, Morphia, Spark Java

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.  

Right, so, on to the codes.  To get started with Morphia 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 Person:

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 save(), list() and 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.  

Image by jplenio from Pixabay



Related Posts

Authenticating Users with Oracle IDCS via OpenId Connect and Micronaut

Authenticating Users with Oracle IDCS via OpenId Connect and Micronaut

Security is the most important aspect of your web application. Fortunately, there are tools available to help make life much easier when dealing with things...

Adding Tracing to Your Distributed Cloud Native Microservices

Adding Tracing to Your Distributed Cloud Native Microservices

When adopting cloud-native technologies and certain architectures such as the microservice pattern, observability and monitoring become a huge need and...

Project GreenThumb Part 5 - The Front-End, Build Pipeline, Push Notifications and Overall Progress

Project GreenThumb Part 5 - The Front-End, Build Pipeline, Push Notifications and Overall Progress

In this short blog series, I introduced you to Project GreenThumb, a project that I created to automate and monitor the process of growing seedlings with...

Note: Comments are currently closed on this blog. Disqus is simply too bloated to justify its use with the low volume of comments on this blog. Please visit my contact page if you have something to say!