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
Please enter at least three characters to search
Refcards Trend Reports
Events Video Library
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

The software you build is only as secure as the code that powers it. Learn how malicious code creeps into your software supply chain.

Apache Cassandra combines the benefits of major NoSQL databases to support data management needs not covered by traditional RDBMS vendors.

Generative AI has transformed nearly every industry. How can you leverage GenAI to improve your productivity and efficiency?

Modernize your data layer. Learn how to design cloud-native database architectures to meet the evolving demands of AI and GenAI workloads.

Related

  • Java and MongoDB Integration: A CRUD Tutorial [Video Tutorial]
  • Apache Cassandra Horizontal Scalability for Java Applications [Book]
  • Introduction to Spring Data JPA, Part 3: Unidirectional One to Many Relations
  • RION - A Fast, Compact, Versatile Data Format

Trending

  • Navigating the LLM Landscape: A Comparative Analysis of Leading Large Language Models
  • Role of Cloud Architecture in Conversational AI
  • Agentic AI and Generative AI: Revolutionizing Decision Making and Automation
  • How to Format Articles for DZone
  1. DZone
  2. Data Engineering
  3. Databases
  4. Using Morphia to Map Java Objects in MongoDB

Using Morphia to Map Java Objects in MongoDB

By 
Geraint Jones user avatar
Geraint Jones
·
Jul. 25, 13 · Interview
Likes (0)
Comment
Save
Tweet
Share
75.7K Views

Join the DZone community and get the full member experience.

Join For Free

MongoDB is an open source document-oriented NoSQL database system which stores data as JSON-like documents with dynamic schemas.  As it doesn't store data in tables as is done in the usual relational database setup, it doesn't map well to the JPA way of storing data. Morphia is an open source lightweight type-safe library designed to bridge the gap between the MongoDB Java driver and domain objects. It can be an alternative to SpringData if you're not using the Spring Framework to interact with MongoDB.

This post will cover the basics of persisting and querying entities along the lines of JPA by using Morphia and a MongoDB database instance.

There are four POJOs this example will be using. First we have BaseEntity which is an abstract class containing the Id and Version fields:

package com.city81.mongodb.morphia.entity;
 
import org.bson.types.ObjectId;
import com.google.code.morphia.annotations.Id;
import com.google.code.morphia.annotations.Property;
import com.google.code.morphia.annotations.Version;
 
public abstract class BaseEntity {
 
    @Id
    @Property("id")
    protected ObjectId id;
 
    @Version
    @Property("version")
    private Long version;
 
    public BaseEntity() {
        super();
    }
 
    public ObjectId getId() {
        return id;
    }
 
    public void setId(ObjectId id) {
        this.id = id;
    }
 
    public Long getVersion() {
        return version;
    }
 
    public void setVersion(Long version) {
        this.version = version;
    }
 
}

Whereas JPA would use @Column to rename the attribute, Morphia uses @Property. Another difference is that @Property needs to be on the variable whereas @Column can be on the variable or the get method.

The main entity we want to persist is the Customer class:

package com.city81.mongodb.morphia.entity;
 
import java.util.List;
import com.google.code.morphia.annotations.Embedded;
import com.google.code.morphia.annotations.Entity;
 
@Entity
public class Customer extends BaseEntity {
 
    private String name;
    private List<Account> accounts;
    @Embedded
    private Address address;
 
    public String getName() {
        return name;
    }
 
    public void setName(String name) {
        this.name = name;
    }
 
    public List<Account> getAccounts() {
        return accounts;
    }
 
    public void setAccounts(List<Account> accounts) {
        this.accounts = accounts;
    }
 
    public Address getAddress() {
        return address;
    }
 
    public void setAddress(Address address) {
        this.address = address;
    }
 
}

As with JPA, the POJO is annotated with @Entity. The class also shows an example of @Embedded:

The Address class is also annotated with @Embedded as shown below:

package com.city81.mongodb.morphia.entity;
 
import com.google.code.morphia.annotations.Embedded;
 
@Embedded
public class Address {
 
    private String number;
    private String street;
    private String town;
    private String postcode;
 
    public String getNumber() {
        return number;
    }
 
    public void setNumber(String number) {
        this.number = number;
    }
 
    public String getStreet() {
        return street;
    }
 
    public void setStreet(String street) {
        this.street = street;
    }
 
    public String getTown() {
        return town;
    }
 
    public void setTown(String town) {
        this.town = town;
    }
 
    public String getPostcode() {
        return postcode;
    }
 
    public void setPostcode(String postcode) {
        this.postcode = postcode;
    }
 
}

Finally, we have the Account class of which the customer class has a collection of:

package com.city81.mongodb.morphia.entity;
 
import com.google.code.morphia.annotations.Entity;
 
@Entity
public class Account extends BaseEntity {
 
    private String name;
 
    public String getName() {
        return name;
    }
 
    public void setName(String name) {
        this.name = name;
    }
 
}

The above show only a small subset of what annotations can be applied to domain classes. More can be found at http://code.google.com/p/morphia/wiki/AllAnnotations

The Example class shown below goes through the steps involved in connecting to the MongoDB instance, populating the entities, persisting them and then retrieving them:

package com.city81.mongodb.morphia;
 
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.List;
import com.city81.mongodb.morphia.entity.Account;
import com.city81.mongodb.morphia.entity.Address;
import com.city81.mongodb.morphia.entity.Customer;
import com.google.code.morphia.Datastore;
import com.google.code.morphia.Key;
import com.google.code.morphia.Morphia;
import com.mongodb.Mongo;
import com.mongodb.MongoException;
 
/**
 * A MongoDB and Morphia Example
 *
 */
public class Example {
 
    public static void main( String[] args ) throws UnknownHostException, MongoException {
 
     String dbName = new String("bank");
     Mongo mongo = new Mongo();
     Morphia morphia = new Morphia();
     Datastore datastore = morphia.createDatastore(mongo, dbName);      
 
     morphia.mapPackage("com.city81.mongodb.morphia.entity");
         
     Address address = new Address();
     address.setNumber("81");
     address.setStreet("Mongo Street");
     address.setTown("City");
     address.setPostcode("CT81 1DB"); 
 
     Account account = new Account();
     account.setName("Personal Account");
 
     List<Account> accounts = new ArrayList<Account>();
     accounts.add(account); 
 
     Customer customer = new Customer();
     customer.setAddress(address);
     customer.setName("Mr Bank Customer");
     customer.setAccounts(accounts);
     
     Key<Customer> savedCustomer = datastore.save(customer);   
     System.out.println(savedCustomer.getId());
 
}

Executing the first few lines will result in the creation of a Datastore. This interface will provide the ability to get, delete and save objects in the 'bank' MongoDB instance.

The mapPackage method call on the morphia object determines what objects are mapped by that instance of Morphia. In this case all those in the package supplied. Other alternatives exist to map classes, including the method map which takes a single class (this method can be chained as the returning object is the morphia object), or passing a Set of classes to the Morphia constructor.

After creating instances of the entities, they can be saved by calling save on the datastore instance and can be found using the primary key via the get method. The output from the Example class would look something like the below:

11-Jul-2012 13:20:06 com.google.code.morphia.logging.MorphiaLoggerFactory chooseLoggerFactory
INFO: LoggerImplFactory set to com.google.code.morphia.logging.jdk.JDKLoggerFactory
4ffd6f7662109325c6eea24f
Mr Bank Customer

There are many other methods on the Datastore interface and they can be found along with the other Javadocs at http://morphia.googlecode.com/svn/site/morphia/apidocs/index.html

An alternative to using the Datastore directly is to use the built in DAO support. This can be done by extending the BasicDAO class as shown below for the Customer entity:

package com.city81.mongodb.morphia.dao;
 
import com.city81.mongodb.morphia.entity.Customer;
import com.google.code.morphia.Morphia;
import com.google.code.morphia.dao.BasicDAO;
import com.mongodb.Mongo;
 
public class CustomerDAO extends BasicDAO<Customer, String> {   
 
    public CustomerDAO(Morphia morphia, Mongo mongo, String dbName) {       
        super(mongo, morphia, dbName);   
    }
 
}

To then make use of this, the Example class can be changed (and enhanced to show a query and a delete):

...
 
     CustomerDAO customerDAO = new CustomerDAO(morphia, mongo, dbName);
     customerDAO.save(customer);
 
     Query<Customer> query = datastore.createQuery(Customer.class);
     query.and(       
       query.criteria("accounts.name").equal("Personal Account"),     
       query.criteria("address.number").equal("81"),       
       query.criteria("name").contains("Bank")
     );      
 
     QueryResults<Customer> retrievedCustomers =  customerDAO.find(query);  
 
     for (Customer retrievedCustomer : retrievedCustomers) {
         System.out.println(retrievedCustomer.getName());   
         System.out.println(retrievedCustomer.getAddress().getPostcode());   
         System.out.println(retrievedCustomer.getAccounts().get(0).getName());
         customerDAO.delete(retrievedCustomer);
     } 
     
...

With the output from running the above shown below:

11-Jul-2012 13:30:46 com.google.code.morphia.logging.MorphiaLoggerFactory chooseLoggerFactory
INFO: LoggerImplFactory set to com.google.code.morphia.logging.jdk.JDKLoggerFactory
Mr Bank Customer
CT81 1DB
Personal Account

This post only covers a few brief basics of Morphia but shows how it can help bridge the gap between JPA and NoSQL.


MongoDB Object (computer science) Relational database Database Java (programming language) Open source

Opinions expressed by DZone contributors are their own.

Related

  • Java and MongoDB Integration: A CRUD Tutorial [Video Tutorial]
  • Apache Cassandra Horizontal Scalability for Java Applications [Book]
  • Introduction to Spring Data JPA, Part 3: Unidirectional One to Many Relations
  • RION - A Fast, Compact, Versatile Data Format

Partner Resources

×

Comments
Oops! Something Went Wrong

The likes didn't load as expected. Please refresh the page and try again.

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • 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:

Likes
There are no likes...yet! 👀
Be the first to like this post!
It looks like you're not logged in.
Sign in to see who liked this post!