For storing data when you’re less concerned about relationships between your data but more interested in entities (documents) and their attributes, a document-based datastore like MongoDB makes a lot of sense. MongoDB’s Java Driver API though is rather clunky in it’s usage pattern.
So I started looking for alternatives. The MongoDB Java ecosystem page has a good collection of some libraries to consider. Initially I took a quick look at MongoJack, which looked like an interesting approach to map between Java POJOs to json data representations (using the Jackson api). I remember reading a while back at Morphia, and was interested what a JPA based approach to interacting with MongoDB would look like. Somewhere I stumbled across the Hibernate OGA project – being a fan of ORM approaches popularized by Hibernate, I wanted to take a look.
The current Hibernate OGM docs (4.1) are here.
For deploying on JBoss/WildFly, OGM is supplied as modules in a zip that you can unzip directly into the modules dir on the server. See here more more details.
Deploying to OpenShift, as for most cartridges, your configuration values are defined in environment variables. Instead of hardcoding the properties and values in your persistence.xml, you can have them passed to your server at startup by adding them to a JAVA_OPTS_EXT file like this (do this one time to create the file):
echo "-Dhibernate.ogm.datastore.host=$OPENSHIFT_MONGODB_DB_HOST \
Mapping your Entities and Id properties
At some point support for the ObjectId MongoDB id type was added. In the current docs don’t use the uuid id generator, use the ‘objectid’ type described here instead:
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Type(type = "objectid")
Here’s what my persistence.xml looks like:
<persistence-unit name="HibernateOGM_PU" transaction-type="JTA">
<!-- Hibernate OGM provider -->
<class>if entities not in same jar, list here</class>
<property name="hibernate.ogm.datastore.provider" value="mongodb" />
<!-- this property is required, and not hibernate.ogm.mongodb.database per docs -->
<property name="hibernate.ogm.datastore.database" value="dbname"/>
<!-- <property name="hibernate.ogm.mongodb.database" value="dbname"/> -->
<!-- host, port, userid and password are from env vars on OpenShift
See example config here https://github.com/hibernate/hibernate-demos/tree/master/hibernate-ogm/hiking-demo
<property name="hibernate.ogm.mongodb.host" value="127.0.0.1"/>
<property name="hibernate.ogm.mongodb.port" value="27017"/>
(Page views: 113)