当前位置:首页 > 开发 > 数据库 > 正文

MongoDB with Morphia

发表于: 2014-04-27   作者:sunjing   来源:转载   浏览:
摘要: mongoDB http://www.mongodb.org/  Morphia https://github.com/mongodb/morphia DZone  http://architects.dzone.com/articles/using-morphia-map-java-objects MongoDB with Querydsl http://blog.my

mongoDB http://www.mongodb.org/ 

Morphia https://github.com/mongodb/morphia

DZone  http://architects.dzone.com/articles/using-morphia-map-java-objects

MongoDB with Querydsl http://blog.mysema.com/2010/11/mongodb-with-querydsl.html

Querydsl  http://www.querydsl.com/


Morphia is a lightweight type-safe library for mapping Java objects to/from MongoDB. Morphia provides a typesafe, and fluent Query API support with (runtime) validation. Morphia uses annotations so there are no XML files to manage or update. Morphia should feel very comfortable for any developer with JPA experience.

 

Features

  • Lifecycle Method/Event Support
  • Works great with Guice, Spring, and other DI frameworks.
  • Many extension points (new annotations, converters, mapping behavior, logging, etc.)
  • Does not store Null/Empty values (by default).
  • GWT support (entities are just POJOs) -- (GWT ignores annotations)
  • Advanced mapper which allows raw conversion, void toObject(DBObject) or DBObject fromObject(Object)

Please continue by reading the QuickStart or looking at a list of the annotations. If you have further questions, please reach out to us on our mailing list.

Quick start
Including morphia in your build

<dependency>
    <groupId>org.mongodb.morphia</groupId>
    <artifactId>morphia</artifactId>
    <version>0.107</version>
</dependency>

See the dependencies page for more detail.

 

Sample code

 

import com.mongodb.DBObject;
import org.bson.types.ObjectId;
import org.mongodb.morphia.Key;
import org.mongodb.morphia.annotations.*;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

 

@Entity("employees")
public class Employee {
    @Id
    private ObjectId id;

 

    // value types are automatically persisted
    private String firstName;

 

    private String lastName;

 

    // only non-null values are stored
    private Long salary = null;

 

    // by default fields are @Embedded
    private Address address;

 

    //references can be saved without automatic loading
    private Key<Employee> manager;

 

    //refs are stored**, and loaded automatically
    @Reference
    private List<Employee> underlings = new ArrayList<Employee>();

 

    // stored in one binary field
    // @Serialized EncryptedReviews;

 

    //fields can be renamed
    @Property("started")
    private Date startDate;

 

    @Property("left")
    private Date endDate;

 

    //fields can be indexed for better performance
    @Indexed
    private boolean active = false;

 

    //fields can loaded, but not saved
    @NotSaved
    private String readButNotStored;

 

    //fields can be ignored (no load/save)
    @Transient
    private int notStored;

 

    //not @Transient, will be ignored by Serialization/GWT for example.
    private transient boolean stored = true;

 

    //Lifecycle methods -- Pre/PostLoad, Pre/PostPersist...
    @PostLoad
    void postLoad(DBObject dbObj) {

    }

 

    public Employee() {

    }

 

    public Employee(String firstName, String lastName, Key<Employee> manager, long salary) {
        this.firstName = firstName;
        this.lastName = lastName;
        this.manager = manager;
        this.salary = salary;
    }

    // getter and setter

    ......

}

 

public class Address {
    private String country;
    private String city;
    private String address;
    private String postcode;

 

    // getter and setter

    ......

}

 

import com.mongodb.Mongo;
import com.mongodb.MongoClient;
import com.mongodb.ServerAddress;
import org.mongodb.morphia.Datastore;
import org.mongodb.morphia.Key;
import org.mongodb.morphia.Morphia;
import org.mongodb.morphia.query.UpdateResults;

import java.net.UnknownHostException;

 

public class EmployeeRepository {
    private Morphia morphia;
    private Datastore ds;

 

    public static void main(String[] args) {
        EmployeeRepository repository = new EmployeeRepository();
        repository.init();
        repository.test();
    }

 

    public void init() {
        try {
            Mongo mongo = new MongoClient(new ServerAddress("localhost", 27017));
            morphia = new Morphia();
            ds = morphia.createDatastore(mongo, "testdb");
        } catch (UnknownHostException e) {
            e.printStackTrace();
        }
    }

 

    public void test() {
        ds.save(new Employee("Mister", "GOD", null, 0L));

 

        // get an employee without a manager
        Employee boss = ds.find(Employee.class).field("manager").equal(null).get();

 

        Key<Employee> scottsKey = ds.save(new Employee("Scott", "Hernandez", ds.getKey(boss), 150 * 1000));

 

        //add Scott as an employee of his manager
        UpdateResults<Employee> res = ds.update(boss, ds.createUpdateOperations(Employee.class).add("underlings", scottsKey));

 

        // get Scott's boss; the same as the one above.
        Employee scottsBoss = ds.find(Employee.class).filter("underlings", scottsKey).get();

 

        for (Employee e : ds.find(Employee.class, "manager", boss))
            System.out.println(e.getLastName() + " " + e.getFirstName());
    }

}

 

Note: @Reference will not save objects, just a reference to them; You must save them yourself.

MongoDB with Morphia

  • 0

    开心

    开心

  • 0

    板砖

    板砖

  • 0

    感动

    感动

  • 0

    有用

    有用

  • 0

    疑问

    疑问

  • 0

    难过

    难过

  • 0

    无聊

    无聊

  • 0

    震惊

    震惊

版权所有 IT知识库 CopyRight © 2009-2015 IT知识库 IT610.com , All Rights Reserved. 京ICP备09083238号