Over a million developers have joined DZone.

Deploying the MongoDB Morphia ODM in OSGi

DZone's Guide to

Deploying the MongoDB Morphia ODM in OSGi

· Java Zone
Free Resource

Bitbucket is for the code that takes us to Mars, decodes the human genome, or drives your next car. What will your code do? Get started with Bitbucket today, it's free.

Morphia is an ODM library for MongoDB. It may be considered as the lightweight alternative of Spring Data MongoDB or as a richer version of Jongo. Compared to Spring Data MongoDB, Morphia is simpler to setup in a non-Spring environment and it has far fewer dependencies. On the other hand, it lacks Spring Data's uniform repository interface, and its convention-over-configuration approach that can boost productivity once a basic configuration has been setup.

The Morphia core JAR is OSGi-ready. However enabling entity class resolution in Morphia when running in OSGi requires some extra steps.

Class loading in Morphia

Morphia's approach to entity class resolution is extensible. It delegates object construction to an instance that implements the org.mongodb.morphia.ObjectFactory interface. Morphia also provides a default implementation - org.mongodb.morphia.mapping.DefaultCreator , which given a com.mongodb.DBObject raw object, it reads its 'className' field, resolves the class and instantiates the respective POJO.

DefaultCreator delegates class resolution to a separate protected method which uses the thread-context class loader (TCCL). Although the TCCL should usually be aware of the entity classes since it is typically called from the DAO layer, this may not always be the case. E.g. in Karaf, during a Blueprint container instantiation, the TCCL is not the instantiating bundle class loader, but Karaf's bootstrap classloader. Overriding the class loading method and delegating to an OSGi-aware classloader provides a more consistent solution.

Entity class resolution in OSGi with Morphia

Here's a customized version of the DefaultCreator that swaps the TCCL class loader with the bundle context class loader:

public class BundleObjectFactory extends DefaultCreator {
	private BundleContext bundleContext;
	protected ClassLoader getClassLoaderForClass() {
		ClassLoader cl = ((BundleWiring)bundleContext.getBundle().adapt(
		return cl;

	public BundleObjectFactory(BundleContext bundleContext) {
		this.bundleContext = bundleContext;

A customized instance of the Morphia class can be created through a factory:

public class MorphiaFactory {
	private BundleContext bundleContext;	
	private List<String> classes;
	private Class<?> loadClass(String className) throws ClassNotFoundException {
		ClassLoader cl = ((BundleWiring)bundleContext.getBundle().adapt(
		return cl.loadClass(className);
	private Mapper getMapper() {
		Mapper mapper = new Mapper();	
		mapper.getOptions().objectFactory = new BundleObjectFactory(bundleContext);		
		return mapper;
	private List<Class<?>> getClassObjects(List<String> classNames) 
		throws ClassNotFoundException {
		if (classNames == null || classNames.size() == 0)
			return null;
		List<Class<?>> classObjs = new ArrayList<>();
		for (String className:classNames) {
		return classObjs;
	public Morphia get() throws ClassNotFoundException {
		Mapper mapper = getMapper();	
		List<Class<?>> classObjs = getClassObjects(classes);
		Morphia morphia = new Morphia(mapper, new HashSet<Class>(classObjs));	
		return morphia;

	public void setBundleContext(BundleContext bundleContext) {
		this.bundleContext = bundleContext;

	public void setClasses(List<String> classes) {
		this.classes = classes;

Blueprint setup

Bringing it all together, using Blueprint for instantiation and wiring, the resulting configuration is:

<blueprint default-activation="eager"
	<cm:property-placeholder persistent-id="io.modio.blog.osgi.morphia"/>

	<bean id="mongoClient" class="com.mongodb.MongoClient">
		<argument value="${io.modio.blog.osgi.morphia.mongodb.host}"/>
		<argument value="${io.modio.blog.osgi.morphia.mongodb.port}"/>
	<bean id="morphiaFactory" class="io.modio.blog.osgi.morphia.MorphiaFactory">
		<property name="bundleContext" ref="blueprintBundleContext"/>
		<property name="classes">
	<bean id="morphia" factory-ref="morphiaFactory" factory-method="get"/>
	<bean id="datastoreFactory" class="io.modio.blog.osgi.morphia.DatastoreFactory">
		<property name="mongoClient" ref="mongoClient"/>
		<property name="morphia" ref="morphia"/>
		<property name="database" value="${io.modio.blog.osgi.morphia.mongodb.db}"/>
	<bean id="datastore" factory-ref="datastoreFactory" factory-method="get"/>
	<!-- DAOs -->	
	<bean id="aclDao" class="io.modio.blog.osgi.morphia.dao.AclDaoImpl">
		<argument ref="datastore"/>
	<bean id="principalDao" class="io.modio.blog.osgi.morphia.dao.PrincipalDaoImpl">
		<argument ref="datastore"/>
	<!-- Services -->
	<service ref="aclDao" interface="io.modio.blog.osgi.morphia.dao.AclDao"/>	
	<service ref="principalDao" interface="io.modio.blog.osgi.morphia.dao.PrincipalDao"/>

The configuration above includes two sample DAOs that implement a simple authentication/authorization service using MongoDB as the persistent store.

The implementation of DatastoreFactory is straight-forward:

public class DatastoreFactory {
	private MongoClient mongoClient;	
	private Morphia morphia;
	private String database;
	public Datastore get() {
		return morphia.createDatastore(mongoClient, database);

	/** get/set methods */

Morphia Karaf feature

When deployed in Karaf, it is useful to group all Morphia's dependencies into a single reusable feature that can then be referenced from other features:

<feature name="morphia" version="0.108" resolver="(obr)">
	<feature version="[1.9.13,2)">jackson</feature>
	<bundle dependency="true">mvn:org.mongodb/mongo-java-driver/2.12.2</bundle>

Bitbucket is the Git solution for professional teams who code with a purpose, not just as a hobby. Get started today, it's free.


Opinions expressed by DZone contributors are their own.


Dev Resources & Solutions Straight to Your Inbox

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.


{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}