1. Install MongoDB under Mac
sudo brew update
sudo brew install MongoDB
sudo brew services MongoDB start
2. Create a mapping class
Package Mongodbdemo;import Org.mongodb.morphia.annotations.entity;import org.mongodb.morphia.annotations.Id; Use Morphia's annotation to annotate @entitypublic class User { @Id private long Id; private String name; Private Boolean sex; private int age; Private String address; Public user () { } public user (long ID, string name, Boolean sex, int age, string address) { super (); This.id = ID; this.name = name; This.sex = sex; This.age = age; this.address = address; } Getter, setter @Override public String toString () { return this.id + "#" + THIS.name + "#" + This.age + "# "+ This.sex +" # "+ this.address; }}
3. Test code
Package Mongodbdemo;import Org.mongodb.morphia.datastore;import Org.mongodb.morphia.morphia;import Com.mongodb.mongoclient;public class Demo {public static void Main (string[] args) { Morphia Morphia = new Morphia (); Tell Morphia where to find your class //Can make multiple calls to different packages or classes morphia.mappackage ("Mongodbdemo"); Create Datastore, and connect to the specified database //datastore has two parameters, the first one to connect to MongoDB, and the second is the name of the database. final Datastore Datastore = Morphia.createdatastore (new mongoclient ("localhost"), "morphia_example"); Datastore.ensureindexes (); Final User user = new User (0, "Zhansan", false,20, "Home"); Datastore.save (user);} }
After running, view the database
4. Source code Download
http://download.csdn.net/detail/mtour/9595523
Using the Morphia framework to manipulate MongoDB