Using Morphia to map Java objects in MongoDB

jieforest發表於2012-07-15
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:

CODE:

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;
    }

}

來自 “ ITPUB部落格 ” ,連結:http://blog.itpub.net/301743/viewspace-735500/,如需轉載,請註明出處,否則將追究法律責任。

相關文章