直接来一个简单的demo:
新建一个maven java project(maven-archetype-quickstart):
DBHelper:
package com.mongo.dao; import com.mongodb.Mongo; import com.mongodb.MongoClient; import org.mongodb.morphia.Datastore; import org.mongodb.morphia.Morphia; /** * Created by hejy on 2016/3/18. */ public class DBHelper { public Datastore ds; public DBHelper(){ //初始化数据 init(); } public void init(){ try{ Mongo mongo = new Mongo("localhost"); MongoClient mongoClient=new MongoClient("localhost"); ds = new Morphia().createDatastore(mongoClient, "mydb"); } catch(Exception e){ e.printStackTrace(); } } }
package com.mongo; import com.mongo.dao.DBHelper; import com.mongo.model.Entry; import org.mongodb.morphia.Datastore; import org.mongodb.morphia.query.Query; import java.util.List; /** * Unit test for simple App. */ public class MongoDBTest { private static DBHelper dbHelper=new DBHelper(); private static Entry en=new Entry(); private static Datastore db=dbHelper.ds; public static void queryAll(){ Query<Entry> query=db.createQuery(Entry.class); List<Entry> list=query.asList(); for(Entry entry:list){ System.out.println(entry); } } public static void add(){ int num=(int)System.currentTimeMillis(); for(int i=0;i<10;i++){ Entry en=new Entry(); en.setId(num++); en.setName("hjy"); db.save(en); } } public static void main(String args[]){ add(); queryAll(); } }
执行结果:
说明:
在操作之前我们不需要给mongodb建立数据库,当我们往数据库中存入数据时,数据库会自动创建。
原文:http://blog.csdn.net/hejingyuan6/article/details/50925845