标签:
1. mac 下 安装mongodb
sudo brew update
sudo brew install mongodb
sudo brew services mongodb start
2. 创建映射类
package mongodbDemo; import org.mongodb.morphia.annotations.Entity; import org.mongodb.morphia.annotations.Id; //利用morphia的annotation进行注解 @Entity public 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. 测试代码
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(); // 告诉Morphia在哪里找到你的类 // 可以为不同的包或者类进行多次的调用 morphia.mapPackage("mongodbDemo"); //创建datastore,并连接到指定数据库 //datastore有两个参数,第一个用来连接到MongoDB,第二个是数据库的名字。 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); } }
运行后,查看数据库
4. 源码下载
http://download.csdn.net/detail/mtour/9595523
标签:
原文地址:http://www.cnblogs.com/mtour/p/5739031.html