DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports
Events Video Library
Over 2 million developers have joined DZone. Join Today! Thanks for visiting DZone today,
Edit Profile Manage Email Subscriptions Moderation Admin Console How to Post to DZone Article Submission Guidelines
View Profile
Sign Out
Refcards
Trend Reports
Events
View Events Video Library
Zones
Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

Integrating PostgreSQL Databases with ANF: Join this workshop to learn how to create a PostgreSQL server using Instaclustr’s managed service

Mobile Database Essentials: Assess data needs, storage requirements, and more when leveraging databases for cloud and edge applications.

Monitoring and Observability for LLMs: Datadog and Google Cloud discuss how to achieve optimal AI model performance.

Automated Testing: The latest on architecture, TDD, and the benefits of AI and low-code tools.

Related

  • Intro to Spring Data MongoDB Reactive and How to Move It to the Cloud
  • Spring Data: Easy MongoDB Migration Using Mongock
  • Advanced Search and Filtering API Using Spring Data and MongoDB
  • Manage Hierarchical Data in MongoDB With Spring

Trending

  • Automated Testing: The Missing Piece of Your CI/CD Puzzle
  • Java Parallel GC Tuning
  • CI/CD Docker: How To Create a CI/CD Pipeline With Jenkins, Containers, and Amazon ECS
  • AWS vs. Azure vs. Google Cloud: Comparing the Top Cloud Providers
  1. DZone
  2. Data Engineering
  3. Databases
  4. Deploying the MongoDB Morphia ODM in OSGi

Deploying the MongoDB Morphia ODM in OSGi

John Georgiadis user avatar by
John Georgiadis
·
Sep. 05, 14 · Interview
Like (0)
Save
Tweet
Share
6.60K Views

Join the DZone community and get the full member experience.

Join For 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;
	
	@Override
	protected ClassLoader getClassLoaderForClass() {
		ClassLoader cl = ((BundleWiring)bundleContext.getBundle().adapt(
			BundleWiring.class)).getClassLoader();
		
		return cl;
	}

	public BundleObjectFactory(BundleContext bundleContext) {
		super();
		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(
			BundleWiring.class)).getClassLoader();
		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) {
			classObjs.add(loadClass(className));
		}		
		return classObjs;
	}
	
	@SuppressWarnings("rawtypes")
	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"
	xmlns="http://www.osgi.org/xmlns/blueprint/v1.0.0" 
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xmlns:cm="http://aries.apache.org/blueprint/xmlns/blueprint-cm/v1.0.0">
	
	<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>
	
	<bean id="morphiaFactory" class="io.modio.blog.osgi.morphia.MorphiaFactory">
		<property name="bundleContext" ref="blueprintBundleContext"/>
		<property name="classes">
			<list>
				<value>io.modio.blog.osgi.morphia.entity.Acl</value>
				<value>io.modio.blog.osgi.morphia.Principal</value>
			</list>
		</property>
	</bean>
	<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>
	<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>
	<bean id="principalDao" class="io.modio.blog.osgi.morphia.dao.PrincipalDaoImpl">
		<argument ref="datastore"/>
	</bean>
        
	<!-- Services -->
	<service ref="aclDao" interface="io.modio.blog.osgi.morphia.dao.AclDao"/>	
	<service ref="principalDao" interface="io.modio.blog.osgi.morphia.dao.PrincipalDao"/>
</blueprint>

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>
	<bundle>wrap:mvn:com.thoughtworks.proxytoys/proxytoys/1.0</bundle>
	<bundle>mvn:org.mongodb.morphia/morphia/0.108</bundle>
</feature>
Oracle Data Mining MongoDB Spring Data

Opinions expressed by DZone contributors are their own.

Related

  • Intro to Spring Data MongoDB Reactive and How to Move It to the Cloud
  • Spring Data: Easy MongoDB Migration Using Mongock
  • Advanced Search and Filtering API Using Spring Data and MongoDB
  • Manage Hierarchical Data in MongoDB With Spring

Comments

Partner Resources

X

ABOUT US

  • About DZone
  • Send feedback
  • Careers
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends: