上两篇文章:http://www.cnblogs.com/hoojo/archive/2011/06/01/2066426.html

http://www.cnblogs.com/hoojo/archive/2011/06/02/2068665.html

介绍到了在MongoDB的控制台完成MongoDB的数据操作、以及通过Java MongoDB 的驱动完成在Java中对MongoDB的操作,通过前两篇文章我们对MongoDB有了全面、深刻的认识和理解。现在我们就看看利用Morphia库来操作MongoDB。

开发环境:

System:Windows

IDE:eclipse、MyEclipse 8

Database:mongoDB

开发依赖库:

JavaEE5、mongo-2.5.3.jar、junit-4.8.2.jar

Email:hoojo_@126.com

Blog:http://blog.csdn.net/IBM_hoojo

http://hoojo.cnblogs.com/

一、准备工作

1、 首先,下载mongoDB对Java支持的驱动包

驱动包下载地址:https://github.com/mongodb/mongo-java-driver/downloads

mongoDB对Java的相关支持、技术:http://www.mongodb.org/display/DOCS/Java+Language+Center

驱动源码下载:https://download.github.com/mongodb-mongo-java-driver-r2.6.1-7-g6037357.zip

在线查看源码:https://github.com/mongodb/mongo-java-driver

Morphia jar包下载:http://code.google.com/p/morphia/downloads/list

2、 下面建立一个JavaProject工程,导入下载下来的驱动包。即可在Java中使用Morphia,目录如下:

二、Java操作MongoDB示例

在本示例之前你需要启动mongod.exe的服务,在你安装mongoDB的目录中,找到mongod.exe启动服务后,下面的程序才能顺利执行;

1、 Java操作mongoDB数据库,操作索引

Mongo mongo = new Mongo();

这样就创建了一个MongoDB的数据库连接对象,它默认连接到当前机器的localhost地址,端口是27017。

DB db = mongo.getDB(“test”);

这样就获得了一个test的数据库,如果mongoDB中没有创建这个数据库也是可以正常运行的。如果你读过上一篇文章就知道,mongoDB可以在没有创建这个数据库的情况下,完成数据的添加操作。当添加的时候,没有这个库,mongoDB会自动创建当前数据库。

得到了db,下一步我们要获取一个“聚集集合DBCollection”,通过db对象的getCollection方法来完成。

DBCollection users = db.getCollection("users");

这样就获得了一个DBCollection,它相当于我们数据库的“表”。

查询所有数据

DBCursor cur = users.find();

while (cur.hasNext()) {

System.out.println(cur.next());

}

用BasicDBObjectBuilder,向users对象中添加数据

user = BasicDBObjectBuilder.start("id", 1546555)

.append("name", "jojo").add("address", "gz")

.append("email", "hoojo_@126.com")

.get();

插入数据

users.insert(user);

可以利用JSON工具来序列化对象数据

JSON.serialize(cur)

完整源码

package com.hoo.test;
 
import java.net.UnknownHostException;
import com.hoo.entity.User;
import com.hoo.util.BasicDBObjectUtils;
import com.mongodb.BasicDBObjectBuilder;
import com.mongodb.DB;
import com.mongodb.DBCollection;
import com.mongodb.DBCursor;
import com.mongodb.DBObject;
import com.mongodb.Mongo;
import com.mongodb.MongoException;
import com.mongodb.util.JSON;
 
/**
 * <b>function:</b> Mongo实例对象的相关方法测试
 * @author hoojo
 * @createDate 2011-5-24 下午02:42:29
 * @file MongoDBTest.java
 * @package com.hoo.test
 * @project MongoDB
 * @blog http://blog.csdn.net/IBM_hoojo
 * @email hoojo_@126.com
 * @version 1.0
 */
public class MongoDBTest {
 
    public static void main(String[] args) throws UnknownHostException, MongoException {
        Mongo mg = new Mongo();
        
        System.out.println("查询所有的Database的名称");
        for (String name : mg.getDatabaseNames()) {
            System.out.println("dbName: " + name);
        }
        
        System.out.println("查询test库中的所有collection集合(表)名称");
        DB db = mg.getDB("test");
        for (String name : db.getCollectionNames()) {
            System.out.println("collectionName: " + name);
        }
        
        System.out.println("添加测试数据");
        DBCollection users = db.getCollection("users");
        try {
            // 用自定义BasicDBObjectUtils工具类,将User Enity对象转换成DBObject
            DBObject user = BasicDBObjectUtils.castModel2DBObject(new User("345567", "jack", 22, "beijin"));
            users.insert(user);
            // 用BasicDBObjectBuilder构建一个DBObject对象
            user = BasicDBObjectBuilder.start("id", 1546555).append("name", "jojo").add("address", "gz").append("email", "hoojo_@126.com").get();
            users.insert(user);
        } catch (Exception e) {
            e.printStackTrace();
        }
        
        System.out.println("游标查询所有users集合数据");
        DBCursor cur = users.find();
        while (cur.hasNext()) {
            System.out.println(cur.next());
        }
        System.out.println("查询游标相关内容");
        System.out.println(cur.count());
        System.out.println(cur.getCursorId());
        System.out.println(cur.getOptions());
        System.out.println(cur.getQuery());
        System.out.println(cur.getSizes().listIterator());
        
        System.out.println(cur.itcount());
        //System.out.println(cur.length());
        System.out.println(cur.size());
        System.out.println(cur.numGetMores());
        System.out.println(cur.curr());
        //System.out.println(cur.toArray().get(0));
        
        System.out.println("显示游标查询到的所有内容: " + JSON.serialize(cur));
    }
}

工具类,将带有getter、setter方法的Java类序列化成DBObject对象

package com.hoo.util;
 
import java.lang.reflect.Method;
import com.mongodb.BasicDBObject;
import com.mongodb.DBObject;
 
/**
 * <b>function:</b> 将Entity/Model转换成DBObject
 * @author hoojo
 * @createDate 2011-5-30下午01:53:08
 * @file BasicDBObjectUtil.java
 * @package com.hoo.util
 * @project MongoDB
 * @blog http://blog.csdn.net/IBM_hoojo
 * @email hoojo_@126.com
 * @version 1.0
 */
publicclass BasicDBObjectUtils {
    public static<T> DBObject castModel2DBObject(T entity) throws Exception {
        Method[] method =  entity.getClass().getMethods();
        
        DBObject dbObject = new BasicDBObject();
        for (Method m : method) {
            //System.out.println(m.getName());
            if (m.getName().startsWith("get")) {
                String name = m.getName().replace("get", "");
                for (Method m2 : method) {
                    if (m2.getName().equals("set" + name)) {
                        name = name.substring(0, 1).toLowerCase() + name.substring(1);
                        Object returnVal = m.invoke(entity, new Object[] {});
                        if (returnVal != null) {
                            //System.out.println(name + " : " + m.invoke(shipping, new Object[] {}));
                            dbObject.put(name, returnVal);
                        }
                    }
                }
            }
        }
        System.out.println("dbObject: " + dbObject);
        return dbObject;
    }
}

2、 完成索引操作,首先建立一个MongoDB4IndexTest.java,基本测试代码如下:

package com.hoo.test;
 
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.List;
import org.bson.types.ObjectId;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import com.mongodb.BasicDBObject;
import com.mongodb.Bytes;
import com.mongodb.DB;
import com.mongodb.DBCollection;
import com.mongodb.DBCursor;
import com.mongodb.DBObject;
import com.mongodb.Mongo;
import com.mongodb.MongoException;
import com.mongodb.QueryOperators;
import com.mongodb.util.JSON;
 
/**
 * <b>function:</b> 实现MongoDB的Index操作
 * @author hoojo
 * @createDate 2011-6-2 下午03:21:23
 * @file MongoDB4IndexTest.java
 * @package com.hoo.test
 * @project MongoDB
 * @blog http://blog.csdn.net/IBM_hoojo
 * @email hoojo_@126.com
 * @version 1.0
 */
public class MongoDB4IndexTest {
    
    private Mongo mg = null;
    private DB db;
    private DBCollection users;
    
    @Before
    public void init() {
        try {
            mg = new Mongo();
            //mg = new Mongo("localhost", 27017);
        } catch (UnknownHostException e) {
            e.printStackTrace();
        } catch (MongoException e) {
            e.printStackTrace();
        }
        //获取temp DB;如果默认没有创建,mongodb会自动创建
        db = mg.getDB("temp");
        //获取users DBCollection;如果默认没有创建,mongodb会自动创建
        users = db.getCollection("users");
    }
    
    @After
    public void destory() {
        if (mg != null)
            mg.close();
        mg = null;
        db = null;
        users = null;
        System.gc();
    }
    
    public void print(Object o) {
        System.out.println(o);
    }
}

3、 下面完成对象Collection的index的操作

/**
 * <b>function:</b> 测试Collection的index相关操作
 * @author hoojo
 * @createDate 2012-2-16 下午08:32:26
 */
@Test
public void testIndex() {
    query();
    
    for (DBObject index : coll.getIndexInfo()) {
        print("IndexInfo: " + index);
    }
    
    coll.dropIndexes();
    //创建索引
    coll.createIndex(new BasicDBObject("name", "idx_name"));
    print(coll.findOne(new BasicDBObject("name", "haha")));
    coll.createIndex(coll.findOne(new BasicDBObject("name", "haha")));
    DBObject o = new BasicDBObject("unique", true);
    //coll.createIndex(coll.findOne(), o);
    
    // 修改索引,如果存在就修改不存在就添加
    coll.ensureIndex(o);
    coll.ensureIndex("age_1");
    coll.ensureIndex(new BasicDBObject("age3_1", 6), new BasicDBObject("ts", -1));
    coll.ensureIndex(new BasicDBObject("age_2", 1), new BasicDBObject( "ts" , 1 ));
    coll.ensureIndex(new BasicDBObject("password", 2), new BasicDBObject( "z" , "idx" ));
    coll.ensureIndex(new BasicDBObject("password", 1), new BasicDBObject( "etc" , "idx" ));
    // 创建唯一索引
    coll.ensureIndex(new BasicDBObject("emial", 2), new BasicDBObject("unique", false));
    // 创建索引,指定索引名称default_index
    coll.ensureIndex(new BasicDBObject("address", 1), new BasicDBObject( "name" , "default_index"));
    // 创建索引对象,索引名称user_index
    coll.ensureIndex(coll.findOne(new BasicDBObject("name", "hoho")), "user_index");
    // 唯一索引
    coll.ensureIndex(coll.findOne(new BasicDBObject("name", "hehe")), "users_index_unique", true);
    
    // 查询所有索引
    for (DBObject index : coll.getIndexInfo()) {
        print("IndexInfo: " + index);
    }
    
    print(DBCollection.genIndexName(coll.findOne()));
    
    //coll.dropIndex(coll.findOne());
    print(DBCollection.genIndexName(new BasicDBObject("password", 2)));
    //coll.dropIndex(DBCollection.genIndexName(new BasicDBObject("password", 2)));
    //coll.dropIndexes();
    //coll.dropIndexes("assword_1");
}

三、Morphia基本操作

1、 morphia可以利用annotation对JavaEntity进行注解,那样我们就可以用morphia操作JavaEntity对象

package com.hoo.entity;
 
import com.google.code.morphia.annotations.Entity;
import com.google.code.morphia.annotations.Id;
 
/**
 * <b>function:</b> JavaEntity对象
 * @author hoojo
 * @createDate 2011-5-31上午11:45:21
 * @file User.java
 * @package com.hoo.entity
 * @project Morphia
 * @blog http://blog.csdn.net/IBM_hoojo
 * @email hoojo_@126.com
 * @version 1.0
 */
//利用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;
    }
}

2、 对Morphia对象一些简单的使用,看看该对象提供了哪些基本的操作方法

package com.hoo.test.morphia;
 
import java.net.UnknownHostException;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import com.google.code.morphia.Datastore;
import com.google.code.morphia.EntityInterceptor;
import com.google.code.morphia.Morphia;
import com.google.code.morphia.mapping.MappedClass;
import com.google.code.morphia.mapping.Mapper;
import com.google.code.morphia.mapping.cache.EntityCache;
import com.hoo.entity.User;
import com.mongodb.BasicDBObjectBuilder;
import com.mongodb.Mongo;
import com.mongodb.MongoException;
 
/**
 * <b>function:</b> morphia对象的简单测试
 * @author hoojo
 * @createDate 2011-5-31上午11:30:20
 * @file MorphiaTest.java
 * @package com.hoo.test
 * @project Morphia
 * @blog http://blog.csdn.net/IBM_hoojo
 * @email hoojo_@126.com
 * @version 1.0
 */
public class MorphiaTest {
    private Mongo mongo;
    private Morphia morphia;
    
    @Before
    public void init() {
        try {
            mongo = new Mongo();
        } catch (UnknownHostException e) {
            e.printStackTrace();
        } catch (MongoException e) {
            e.printStackTrace();
        }
        morphia = new Morphia();
    }
    
    private void print(Object o) {
        if (o != null) {
            System.out.println(o.toString());
        }
    }
    
    /**
     * <b>function:</b> morphia对象的简单测试
     * @author hoojo
     */
    @SuppressWarnings("deprecation")
    @Test
    public void testMorphia() {
        // 创建一个Datastore,过时的方法不推荐使用
        Datastore ds = morphia.createDatastore("myTestDB");
        print("createDatastore: " + ds);
        // 创建ds
        ds = morphia.createDatastore(mongo, "myTestDB");
        print("createDatastore: " + ds);
        // 创建一个带用户名、密码的ds
        //ds = morphia.createDatastore(mongo, "myTestDB", "admin", new char[] { '1', '2', '3', '4', '5', '6' });
        
        // 设置操作资源对象,这里设置User.class 就可以完成对User的一系列操作
        //morphia.map(User.class);
        //morphia.mapPackage("com.hoo.entity");//会把整个包下面的类都加载进来
        // 将对象转成DBObject
        print("toDBObject: " + morphia.toDBObject(new User(System.currentTimeMillis(), "jackson", true, 22, null)));
        // 将参数2转换成参数1的类型
        print("fromDBObject: " + morphia.fromDBObject(User.class, BasicDBObjectBuilder.start("sex", true).get()));
        print("getMapper: " + morphia.getMapper());
        print("isMapped: " + morphia.isMapped(User.class));
        
    }
    
    /**
     * <b>function:</b> 对Mapper对象相关操作
     * @author hoojo
     * @createDate 2012-2-16下午10:20:38
     */
    @Test
    public void testMapper() {
        Mapper mapper = morphia.getMapper();
        // 添加对象映射
        print("addMappedClass: " + mapper.addMappedClass(User.class));
        //print(mapper.addMappedClass(mapper.addMappedClass(User.class));
        
        // 创建实体缓存
        print("createEntityCache: " + mapper.createEntityCache());
        print(mapper.getCollectionName("myTestDB"));
        print(mapper.getConverters());
        User user = new User(System.currentTimeMillis(), "jackson", true, 22, null);
        user.setId(1306814012734L);
        print(mapper.getId(user));
        
        for (EntityInterceptor ei : mapper.getInterceptors()) {
            System.out.println("EntityInterceptor: " + ei);
        }
 
        // 查询主键
        print("getKey: " + mapper.getKey(user));
        // 所有已经映射的class
        for (MappedClass mc : mapper.getMappedClasses()) {
            System.out.println("getMappedClasses: " + mc);
        }
        
        print("mcMap: " + mapper.getMCMap());
        
        print("getOptions: " + mapper.getOptions());
        print("keyToRef: " + mapper.keyToRef(mapper.getKey(user)));
        print("refToKey: " + mapper.refToKey(mapper.keyToRef(mapper.getKey(user))));
    }
    
    /**
     * <b>function:</b> 实体缓存
     * @author hoojo
     */
    @Test
    public void testEntityCache() {
        EntityCache ec = morphia.getMapper().createEntityCache();
        print("EntityCache: " + ec);
        Datastore ds = morphia.createDatastore(mongo, "myTestDB");
        User user = new User(System.currentTimeMillis(), "jackson", true, 22, null);
        user.setId(1306814012734L);
        
        // 添加实体
        ec.putEntity(ds.getKey(user), user);
        // 代理
        ec.putProxy(ds.getKey(user), user);
        
        print("getKey: " + ds.getKey(user));
        print("getProxy: " + ec.getProxy(ds.getKey(user)));
        print("getEntity: " + ec.getEntity(ds.getKey(user)));
        
        print(ec.exists(ds.getKey(user)));
        
        print("stats: " + ec.stats());
    }
    
    @After
    public void destory() {
        mongo = null;
        morphia = null;
        System.gc();
    }
}

四、利用Morphia完成对Datastore对象的CRUD操作

1、 首先添加如下准备代码,随后的方法直接添加到该文件中即可

package com.hoo.test.ds;
 
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.List;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import com.google.code.morphia.Datastore;
import com.google.code.morphia.Key;
import com.google.code.morphia.Morphia;
import com.google.code.morphia.query.UpdateOperations;
import com.hoo.entity.User;
import com.mongodb.Mongo;
import com.mongodb.MongoException;
 
/**
 * <b>function:</b> Datastore增删改查操作
 * @author hoojo
 * @createDate 2011-5-31下午06:29:04
 * @fileDatastore DatastoreTest.java
 * @package com.hoo.test.ds
 * @project Morphia
 * @blog http://blog.csdn.net/IBM_hoojo
 * @email hoojo_@126.com
 * @version 1.0
 */
public class DatastoreTest {
    private Mongo mongo;
    private Morphia morphia;
    private Datastore ds;
    
    @Before
    public void init() {
        try {
            mongo = new Mongo();
        } catch (UnknownHostException e) {
            e.printStackTrace();
        } catch (MongoException e) {
            e.printStackTrace();
        }
        morphia = new Morphia();
        morphia.map(User.class);
        ds = morphia.createDatastore(mongo, "temp");
    }
    
    private void print(Object o) {
        if (o != null) {
            System.out.println(o.toString());
        }
    }
    
    
    /**
    * <b>function:</b> 查询所有
    * @author hoojo
    * @createDate 2012-2-16 下午10:36:13
    */
    private void query() {
        Iterable<User> it = ds.createQuery(User.class).fetch();
        while(it.iterator().hasNext()) {
            print("fetch: " + it.iterator().next());
        }
    }
    
    @After
    public void destory() {
        mongo = null;
        morphia = null;
        ds = null;
        System.gc();
    }
}

2、 增删改CUD操作

/**
 * <b>function:</b> CUD增删改
 * @author hoojo
 * @createDate 2012-2-16 下午10:46:08
 */
@Test
public void testCUD() {
    // 添加测试数据
    for (int i = 0; i < 50; i++) {
        User u = new User(System.currentTimeMillis() + i, "test-" + i, ((i % 2 == 0)? true: false), 18 + i, "china-gz#" + i);
        print(ds.save(u));
    }
    //ds.delete(ds.createQuery(User.class));
    
    List<User> users = new ArrayList<User>();
    users.add(new User(1306907246518L, "zhangsan", true, 22, "china-gz"));
    User user = new User(System.currentTimeMillis() + 3, "zhaoliu", true, 29, "china-beijin");
    users.add(user);
    users.add(new User(System.currentTimeMillis() + 6, "wangwu", true, 24, "china-shanghai"));
    users.add(new User(System.currentTimeMillis() + 9, "lisi", true, 26, "china-wuhan"));
    //添加集合
    print("save: " + ds.save(users));
    
    //添加数组
    print("save: " + ds.save(users.toArray()));
    
    this.query();
    print("getKey: " + ds.find(User.class, "id", 1306907246518L).getKey());
    
    //修改操作
    UpdateOperations<User> uo = ds.createUpdateOperations(User.class);
    
    print("update: " + ds.update(ds.find(User.class, "id", 1306907246518L).getKey(), uo).getUpdatedCount());
    uo.add("name", "zhaoliuliu").set("age", 29).set("sex", true).add("address", "gzz");
    print("update: " + ds.update(ds.find(User.class, "id", 1306907246518L).getKey(), uo).getUpdatedCount());
 
    print("update: " + ds.update(ds.createQuery(User.class).field("id").equal(1306907246518L), uo).getUpdatedCount());
    print("update: " + ds.update(ds.find(User.class, "id", 1306907246518L), uo).getUpdatedCount());
    
    uo = ds.createUpdateOperations(User.class);
    uo.set("name", "zhaoqq").set("age", 29).set("sex", true).add("address", "fzz");
    print("update: " + ds.update(ds.find(User.class, "id", 1306907246518L).get(), uo).getUpdatedCount());
    
    print("update: " + ds.update(ds.createQuery(User.class).field("id").equal(1306907246518L), uo, true).getUpdatedCount());
    
    // 修改第一个对象
    print("updateFirst: " + ds.updateFirst(ds.createQuery(User.class).field("id").equal(1306907246518L), uo).getUpdatedCount());
    //当参数createIfMissing为true的时候,如果修改的对象不存在就会添加这条数据,如果为false的情况下,不存在也不添加
    print("updateFirst: " + ds.updateFirst(ds.createQuery(User.class).field("id").equal(1306907246519L), uo, true).getUpdatedCount());
    user.setId(1306907246518L);
    print("updateFirst: " + ds.updateFirst(ds.createQuery(User.class).field("id").equal(1306907246518L), user, true).getUpdatedCount());
    
    user.setId(1306916670518L);
    // 合并
    print("merge: " + ds.merge(user).getId());
    this.query();
    
    //删除
    print("delete: " + ds.delete(ds.createQuery(User.class).field("id").equal(1306907246518L)).getN());
    print("delete: " + ds.delete(ds.find(User.class, "age", 29).get()).getN());
    //print("delete: " + ds.delete(User.class, 1306911594631L).getN());
    //print("delete: " + ds.delete(User.class, users).getN());
    //ds.delete(ds.createQuery(User.class));
    this.query();
}

3、 Find查询操作

/**
 * <b>function:</b> find查询
 * @author hoojo
 * @createDate 2012-2-16 下午10:45:55
 */
@Test
public void testFind() {
    print("find: " + ds.find(User.class).asList());
    //like
    print("find-contains: " + ds.find(User.class).field("name").contains("test-1").asList());
    //忽略大小写
    print("find-containsIgnoreCase: " + ds.find(User.class).field("name").containsIgnoreCase("ja").asList());
    
    print("find-endsWith: " + ds.find(User.class).field("name").endsWith("22").asList());
    print("find-endsWithIgnoreCase: " + ds.find(User.class).field("name").endsWithIgnoreCase("CK").asList());
    
    //过滤null或是没有name属性的
    print("find-doesNotExist: " + ds.find(User.class).field("name").doesNotExist().asList());
    //查询name有值的数据
    print("find-doesNotExist: " + ds.find(User.class).field("name").exists().asList());
    //age > 48
    print("find-greaterThan: " + ds.find(User.class).field("age").greaterThan(66).asList());
    //age >= 48
    print("find-greaterThan: " + ds.find(User.class).field("age").greaterThanOrEq(66).asList());
    
    List<Integer> ageList = new ArrayList<Integer>(); 
    ageList.add(22);
    ageList.add(55);
    ageList.add(66);
    //all
    print("find-hasAllOf: " + ds.find(User.class).field("age").hasAllOf(ageList).asList());
    //in
    print("find-hasAnyOf: " + ds.find(User.class).field("age").hasAnyOf(ageList).asList());
    //not in
    print("find-hasNoneOf: " + ds.find(User.class).field("age").hasNoneOf(ageList).asList());
    //elemMatch
    //print("find-hasThisElement: " + ds.find(User.class).field("age").hasThisElement(55).asList());
    print("find-hasThisOne: " + ds.find(User.class).field("age").hasThisOne(55).asList());
    
    print("find-in: " + ds.find(User.class).field("age").in(ageList).asList());
    print("find-lessThan: " + ds.find(User.class).field("age").lessThan(20).asList());
    print("find-lessThanOrEq: " + ds.find(User.class).field("age").lessThanOrEq(18).asList());
    
    //print("find-lessThanOrEq: " + ds.find(User.class).field("age").near(.2, .8).asList());
    
    print("find: " + ds.find(User.class, "id", 1306813979609L).get());
    print("find: " + ds.find(User.class, "age", 28, 1, 2).asList());
    
    print("findAndDelete: " + ds.findAndDelete(ds.createQuery(User.class).field("id").equal(1306813979609L)));
    print("find: " + ds.find(User.class).asList());
}

4、 Query查询操作

/**
 * <b>function:</b> query查询
 * @author hoojo
 * @createDate 2012-2-16 下午10:40:10
 */
@Test
public void testQuery() {
    // 查询所有
    print("query: " + ds.createQuery(User.class).asList());
    // 查询主键
    print("query key: " + ds.createQuery(User.class).asKeyList());
    // 结果集数量
    print("query: " + ds.createQuery(User.class).countAll());
    // 抓取查询所有记录
    Iterable<User> it = ds.createQuery(User.class).fetch();
    while(it.iterator().hasNext()) {
        print("fetch: " + it.iterator().next());
    }
    
    // null 
    it = ds.createQuery(User.class).fetchEmptyEntities();
    while(it.iterator().hasNext()) {
        print("fetchEmptyEntities: " + it.iterator().next());
    }
    
    // all key
    Iterable<Key<User>> itkeys = ds.createQuery(User.class).fetchKeys();
    while(itkeys.iterator().hasNext()) {
        print("fetchKeys: " + itkeys.iterator().next());
    }
    
    // age > 24
    print("query: " + ds.createQuery(User.class).filter("age > ", 24).asList());
    // age in (20, 28)
    print("query: " + ds.createQuery(User.class).filter("age in ", newint[] { 20, 28 }).asList());
    
    // limit 3
    print("query: " + ds.createQuery(User.class).limit(3).asList());
    // 分页类似MySQL
    print("query: " + ds.createQuery(User.class).offset(11).limit(5).asList());
    // order排序,默认asc
    print("query: " + ds.createQuery(User.class).order("age").asList());
    //desc
    print("query: " + ds.createQuery(User.class).order("-age").asList());
    // 组合排序 order by age, name
    print("query: " + ds.createQuery(User.class).order("age, name").asList());
    
    print("query: " + ds.createQuery(User.class).queryNonPrimary().asList());
    print("query: " + ds.createQuery(User.class).queryPrimaryOnly().asList());
    //如果include 为true就表示取该属性的值,其他的默认null,反之为false则该属性为null,取其他的值
    print("query: " + ds.createQuery(User.class).retrievedFields(false, "age").asList());
}

5、 get和count查询

/**
 * <b>function:</b> get查询
 * @author hoojo
 * @createDate 2012-2-16 下午10:39:09
 */
@Test
public void testGet() {
    User user = new User();
    user.setId(1306916670518L);
    print("get: " + ds.get(user));
    List<Long> ids = new ArrayList<Long>();
    ids.add(1306907246519L);
    ids.add(1306916670524L);
    // 通过id集合查询相当于in ()
    print("get: " + ds.get(User.class, ids).asList());
    // id查询
    print("get: " + ds.get(User.class, 1306916670524L));
}
 
/**
 * <b>function:</b> count查询
 * @author hoojo
 * @createDate 2012-2-16 下午10:38:02
 */
@Test
public void testGetCount() {
    User user = new User();
    user.setId(1306916670518L);
    print("getCount: " + ds.getCount(user));
    print("getCount: " + ds.getCount(User.class));
    
    List<Long> ids = new ArrayList<Long>();
    ids.add(1306907246519L);
    ids.add(1306916670524L);
    print("getCount: " + ds.getCount(ds.get(User.class, ids)));
    
    // age > 22的记录
    print("getCount: " + ds.getCount(ds.createQuery(User.class).filter("age > ", 22)));
    // 所有
    print("countAll: " + ds.get(User.class, ids).countAll());
    print("countAll: " + ds.find(User.class).countAll());
}

6、 其他操作

@Test
public void testOthers() {
    query();
    /** 索引 */
    ds.ensureIndexes(); 
    // 同时用annotation也可以给指定的属性建立索引
    // 只需用在JavaEntity建立索引的属性上添加annotation
    /*@Indexed(value = IndexDirection.ASC, name = "address_index")
    String address;
    // 建立唯一索引
    @Indexed(value = IndexDirection.ASC, name = "bandName", unique = true)
    String name;*/
 
    ds.ensureCaps();
    User user = new User();
    user.setId(1306916670518L);
    print("getDB: " + ds.getDB());
    print("getDefaultWriteConcern: " + ds.getDefaultWriteConcern());
    print("DBColl: " + ds.getCollection(User.class)); // 查询User对象对应的集合
    Key<User> key = ds.getKey(user); // 主键
    print("getKey: " + key);
    print("exists: " + ds.exists(user)); //是否存在该对象
    print("exists: " + ds.exists(ds.getKey(user)));
    
    print("getByKey: " + ds.getByKey(User.class, key));
    List<Key<User>> keys = new ArrayList<Key<User>>();
    keys.add(key);
    user.setId(1306916670521L);
    keys.add(ds.getKey(user));
    print("getByKey: " + ds.getByKeys(keys));
    print("getByKey: " + ds.getByKeys(User.class, keys));
    
    query();
}

用Morphia操作对象相对比较简单,它对MongoDB对Java的操作进行了一些封装,特别是查询这方面的。有没有感觉像是在用Hibernate?

NoSQL 之 Morphia 操作 MongoDB的更多相关文章

  1. mongoose - 让node.js高效操作mongodb

    Mongoose库简而言之就是在node环境中操作MongoDB数据库的一种便捷的封装,一种对象模型工具,类似ORM,Mongoose将数据库中的数据转换为JavaScript对象以供你在应用中使用. ...

  2. Python 操作 mongodb 数据库

    原文地址:https://serholiu.com/python-mongodb 这几天在学习Python Web开发,于 是做准备做一个博客来练练手,当然,只是练手的,博客界有WordPress这样 ...

  3. PHP操作MongoDB简明教程(转)

    转自:http://blog.sina.com.cn/s/blog_6324c2380100ux2m.html MongoDB是最近比较流行的NoSQL数据库,网络上关于PHP操作MongoDB的资料 ...

  4. Mongodb入门并使用java操作Mongodb

    转载请注意出处:http://blog.csdn.net/zcm101 最近在学习NoSql,先从Mongodb入手,把最近学习的总结下. Mongodb下载安装 Mongodb的下载安装就不详细说了 ...

  5. node.js高效操作mongodb

    node.js高效操作mongodb Mongoose库简而言之就是在node环境中操作MongoDB数据库的一种便捷的封装,一种对象模型工具,类似ORM,Mongoose将数据库中的数据转换为Jav ...

  6. 浅谈如何用Java操作MongoDB

    NoSQL数据库因其可扩展性使其变得越来越流行,利用NoSQL数据库可以给你带来更多的好处,MongoDB是一个用C++编写的可度可扩展性的开源NoSQL数据库.本文主要讲述如何使用Java操作Mon ...

  7. 使用Python操作MongoDB

    MongoDB简介(摘自:http://www.runoob.com/mongodb/mongodb-intro.html) MongoDB 由C++语言编写,是一个基于分布式文件存储的开源数据库系统 ...

  8. Python操作MongoDB和Redis

    1. python对mongo的常见CURD的操作 1.1 mongo简介 mongodb是一个nosql数据库,无结构化.和去中心化. 那为什么要用mongo来存呢? 1. 首先.数据关系复杂,没有 ...

  9. mongoose之操作mongoDB数据库

    mongoose是node.js操作mongoDB数据库的一种工具,借助于mongoose,我们可以便捷的完成一些数据库的基本操作,基本使用如下: 1.安装 npm install mongoose ...

随机推荐

  1. hdu1158【DP】

    题意: 第一行项目数: 第二行每个工人的Hire Salary Fire money 第三行每个项目需要的人的数量: 工人在hire/fire的时候要付出额外的钱,如果已经hire了还没有fire就一 ...

  2. zookeeper 搭建

    zookeeper 版本为zookeeper 3.4.8 操作系统为ubuntu 12.04 64位 zookeeper 单机搭建 解压zookeeper 包 .tar.gz -C /root/sof ...

  3. 单片机的C语言中位操作用法

    在对单处机进行编程的过程中,对位的操作是经常遇到的.C51对位的操控能力是非常强大的.从这一点上,就可以看出C不光具有高级语言的灵活性,又有低级语言贴近硬件的特点.这也是在各个领域中都可以看到C的重要 ...

  4. HDU-1556:Color the ball(前缀和)

    Color the ball Time Limit: 9000/3000 MS (Java/Others)    Memory Limit: 32768/32768 K (Java/Others) T ...

  5. (洛谷 P1429 平面最近点对(加强版) || 洛谷 P1257 || Quoit Design HDU - 1007 ) && Raid POJ - 3714

    这个讲的好: https://phoenixzhao.github.io/%E6%B1%82%E6%9C%80%E8%BF%91%E5%AF%B9%E7%9A%84%E4%B8%89%E7%A7%8D ...

  6. centOS 7联网

    在windows上安装的centOS7虚拟机要联网后才能正常使用,只需这样配置下即可: 打开vim /etc/sysconfig/network-scripts/ifcfg-eno16777736,会 ...

  7. JetSpeed2因dom4j包冲突导致PSML页面文件数据丢失

    使用JetSpeed2进行二次开发时突然出现在保存Portlet配置信息时出现PSML页面文件数据丢失的情况,几经测试,最终发现是因为Portlet中的dom4j.jar与jetspeed应用中的do ...

  8. 【aspnetcore】让aspnetcore支持less文件

    第一步:新建文件 CustomerFileExtensionContentTypeProvider namespace xxx { public class CustomerFileExtension ...

  9. csu 1552: Friends 二分图 + Miller_Rabin

    http://acm.csu.edu.cn/csuoj/problemset/problem?pid=1552 把那n个数写两次,分成相同的两堆,判断相加是质数的,连一条边,然后找最大匹配,ans = ...

  10. 06.Javascript——入门this的用法(难点)

    this 的指向 this 是 js 中定义的关键字,它自动定义于每一个函数域内,但是它的指向却让人很迷惑.在实际应用中,this 的指向大致可以分为以下四种情况. 1.作为普通函数调用 当函数作为一 ...