MongoDB + Morphia 入门

Mongodb 是最近很流行的NO sql DB。非关系型数据库的典型。非常适合厌倦了SQL 的你。

不废话,开始

1 上官网 http://www.mongodb.org/

    这个是我xp使用的Windows 32位 版本,限制是DB只能使用2G

http://downloads.mongodb.org/win32/mongodb-win32-i386-2.0.1.zip

自己下载,解压

 

2 打开 bin目录,例如我的:

C:\soft\mongodb-win32-i386-2.0.0\bin

让我们建立一个启动的脚本(bat)吧,免得每次都命令:

mongod.exe --journal -dbpath C:\soft\mongodb-win32-i386-2.0.0\db

mongod.exe是服务器程序

mongo.exe 是 admin console

--journal 持续运行

-dbpath C:\soft\mongodb-win32-i386-2.0.0\db 指定db存放的目录

运行这个 脚本。

控制台显示:

C:\soft\mongodb-win32-i386-2.0.0\bin>mongod.exe --journal -dbpath C:\soft\mongod
b-win32-i386-2.0.0\db
Mon Oct 24 18:12:29 [initandlisten] MongoDB starting : pid=6100 port=27017 dbpat
h=C:\soft\mongodb-win32-i386-2.0.0\db 32-bit host=xxx
Mon Oct 24 18:12:29 [initandlisten]
Mon Oct 24 18:12:29 [initandlisten] ** NOTE: when using MongoDB 32 bit, you are
limited to about 2 gigabytes of data
Mon Oct 24 18:12:29 [initandlisten] **       see http://blog.mongodb.org/post/13
7788967/32-bit-limitations
Mon Oct 24 18:12:29 [initandlisten] **       with --journal, the limit is lower
Mon Oct 24 18:12:29 [initandlisten]
Mon Oct 24 18:12:29 [initandlisten] db version v2.0.0, pdfile version 4.5
Mon Oct 24 18:12:29 [initandlisten] git version: 695c67dff0ffc361b8568a13366f027
caa406222
Mon Oct 24 18:12:29 [initandlisten] build info: windows (5, 1, 2600, 2, 'Service
 Pack 3') BOOST_LIB_VERSION=1_42
Mon Oct 24 18:12:29 [initandlisten] options: { dbpath: "C:\soft\mongodb-win32-i3
86-2.0.0\db", journal: true }
Mon Oct 24 18:12:29 [initandlisten] journal dir=C:/soft/mongodb-win32-i386-2.0.0
/db/journal
Mon Oct 24 18:12:29 [initandlisten] recover : no journal files present, no recov
ery needed
Mon Oct 24 18:12:29 [websvr] admin web console waiting for connections on port 2
8017
Mon Oct 24 18:12:29 [initandlisten] waiting for connections on port 27017

 

 

打开页面 http://127.0.0.1:27017/

显示

You are trying to access MongoDB on the native driver port. For http diagnostic access, add 1000 to the port number

 

 

 

就说明你运行成功了。

 

 

 

3 提供一下用到的POJO:

import org.bson.types.ObjectId;

import com.google.code.morphia.annotations.Embedded;
import com.google.code.morphia.annotations.Entity;
import com.google.code.morphia.annotations.Id;
@Entity
public class Hotel {
	@Id
	private ObjectId id;
	private String name;
	private int stars;
	@Embedded
	private Address address;

	
	
	public ObjectId getId() {
		return id;
	}

	public void setId(ObjectId id) {
		this.id = id;
	}

	// ... getters and setters
	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public int getStars() {
		return stars;
	}

	public void setStars(int stars) {
		this.stars = stars;
	}

	public Address getAddress() {
		return address;
	}

	public void setAddress(Address address) {
		this.address = address;
	}

}

 

 

import com.google.code.morphia.annotations.Embedded;

@Embedded
public class Address {
	private String street;
	private String city;
	private String postCode;
	private String country; // ... getters and setters

	public String getStreet() {
		return street;
	}

	public void setStreet(String street) {
		this.street = street;
	}

	public String getCity() {
		return city;
	}

	public void setCity(String city) {
		this.city = city;
	}

	public String getPostCode() {
		return postCode;
	}

	public void setPostCode(String postCode) {
		this.postCode = postCode;
	}

	public String getCountry() {
		return country;
	}

	public void setCountry(String country) {
		this.country = country;
	}

}

 4 需要下载数据库的java 驱动

http://github.com/mongodb/mongo-java-driver/downloads

需要参考的驱动API

http://api.mongodb.org/java/

 

 

 

5 example

 这个是单纯MoongoDb 支持的 API 操作,不解释。这是直接操作DB

还没有完成ORM操作。上代码。

import java.net.UnknownHostException;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;
import java.util.Set;

import org.junit.Before;
import org.junit.Test;

import com.mongodb.BasicDBObject;
import com.mongodb.DB;
import com.mongodb.DBCollection;
import com.mongodb.DBCursor;
import com.mongodb.DBObject;
import com.mongodb.Mongo;
import com.mongodb.MongoException;

public class MongoTest {
	public static void main(String[] args) {

	}

	private Mongo m;
	private DB db;

	@Before
	public void init() {

		try {
			// new a Mongo Object ,entrance for accessing MongoDb
			this.m = new Mongo("localhost");
			System.out.println(m.debugString());
			// // select a DB
			// // The database doesn't have to exist - if it doesn't, MongoDB
			// will create it for you.
			this.db = m.getDB("test");
			System.out.println("DB [" + db.getName() + "] Connected");
		} catch (UnknownHostException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (MongoException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	@Test
	public void testCases() {
		// TODO Auto-generated method stub
		testFindAlltestFindAllCollections();

		insertFindAllRemove();
		insertFindOneRemove();
		insertAndQuery();
		createIndex();

		;
	}

	private void createIndex() {
		insertRecords();
		// MongoDB supports indexes, and they are very easy to add on a
		// collection. To create an index, you just specify the field that
		// should be indexed, and specify if you want the index to be ascending
		// (1) or descending (-1). The following creates an ascending index on
		// the "i" field :
		DBCollection dbconn = db.getCollection("things");
		dbconn.createIndex(new BasicDBObject("case", -1)); // create index on "i",
														// ascending
		
		Iterator<DBObject> iter=	dbconn.getIndexInfo().iterator();
		while (iter.hasNext()) {
			DBObject dbObject = (DBObject) iter.next();
			System.out.println("Index Info:"+dbObject);;
		}
		removeAll();
	}

	private void insertAndQuery() {
		insertRecords();
		query();
		removeAll();
	}

	private void query() {
		System.out.println("start  query");
		DBCollection dbconn = db.getCollection("things");
		// looks like find by example
		BasicDBObject queryDb = new BasicDBObject();
		queryDb.append("case", 5);
		DBCursor dbc = dbconn.find(queryDb);
		while (dbc.hasNext()) {
			DBObject dbObject = (DBObject) dbc.next();
			System.out.println("result case=5:" + dbObject);
		}
		System.out.println("end  query");

		// find in range

		BasicDBObject query = new BasicDBObject();

		query.put("case", new BasicDBObject("$gt", 5)); // e.g. find all where
														// case > 5

		DBCursor cur = dbconn.find(query);

		while (cur.hasNext()) {
			System.out.println("case >5:" + cur.next());
		}

	}

	private void insertFindOneRemove() {
		insertRecords();
		testFindOneInCollections();
		removeAll();

	}

	private void testFindOneInCollections() {
		System.out.println("Collections Find one:");
		DBCollection dbconn = db.getCollection("things");
		// declare that just one object is needed,null if none
		System.out.println(dbconn.findOne());
		;
		System.out.println("Collections Find one end");
	}

	private void insertFindAllRemove() {
		insertRecords();
		testFindAllInCollections();
		removeAll();

	}

	private void removeAll() {
		System.out.println("start remove all");
		DBCollection dbconn = db.getCollection("things");
		DBCursor c = dbconn.find();
		while (c.hasNext()) {
			dbconn.remove(c.next());
		}
		System.out.println("done");
	}

	public void testFindAlltestFindAllCollections() {
		System.out.println("Collections :");
		Set<String> colls = db.getCollectionNames();
		for (String s : colls) {
			System.out.print(s);
			System.out.print(",");

		}
		System.out.println();
	}

	public void insertRecords() {
		System.out.println("start insert :");
		DBCollection dbconn = db.getCollection("things");
		for (int i = 0; i < 10L; i++) {
			// BasicDBObject basic=new BasicDBObject();
			//
			// basic.append("time",System.currentTimeMillis());
			//
			// basic.append("obj",i);
			// dbconn.save(basic);
			BasicDBObject doc = new BasicDBObject();
			doc.put("case", i);
			doc.put("name", "MongoDB");
			doc.put("type", "database");
			doc.put("count", 1);

			BasicDBObject info = new BasicDBObject();

			info.put("x", 203);
			info.put("y", 102);

			doc.put("info", info);

			dbconn.insert(doc);

		}
		System.out.println("Insert End");
	}

	public void testFindAllInCollections() {
		System.out.println("Data in 'things':");

		// Select a Collection ,Collection looks like a Table of RMDBS
		DBCollection coll = db.getCollection("things");
		// find all and print

		DBCursor c = coll.find();
		while (c.hasNext()) {
			System.out.println(c.next());

		}

	}
}

 

输出结果:

DBTCPConnector: localhost:27017 A1569XDZXLJM8W6/133.4.0.85:27017
DB [test] Connected
Collections :
system.indexes,things,
start insert :
Insert End
Data in 'things':
{ "_id" : { "$oid" : "4eb75882ba4d4fab62ee4cfb"} , "case" : 0 , "name" : "MongoDB" , "type" : "database" , "count" : 1 , "info" : { "x" : 203 , "y" : 102}}
{ "_id" : { "$oid" : "4eb75882ba4d4fab62ee4cfc"} , "case" : 1 , "name" : "MongoDB" , "type" : "database" , "count" : 1 , "info" : { "x" : 203 , "y" : 102}}
{ "_id" : { "$oid" : "4eb75882ba4d4fab62ee4cfd"} , "case" : 2 , "name" : "MongoDB" , "type" : "database" , "count" : 1 , "info" : { "x" : 203 , "y" : 102}}
{ "_id" : { "$oid" : "4eb75882ba4d4fab62ee4cfe"} , "case" : 3 , "name" : "MongoDB" , "type" : "database" , "count" : 1 , "info" : { "x" : 203 , "y" : 102}}
{ "_id" : { "$oid" : "4eb75882ba4d4fab62ee4cff"} , "case" : 4 , "name" : "MongoDB" , "type" : "database" , "count" : 1 , "info" : { "x" : 203 , "y" : 102}}
{ "_id" : { "$oid" : "4eb75882ba4d4fab62ee4d00"} , "case" : 5 , "name" : "MongoDB" , "type" : "database" , "count" : 1 , "info" : { "x" : 203 , "y" : 102}}
{ "_id" : { "$oid" : "4eb75882ba4d4fab62ee4d01"} , "case" : 6 , "name" : "MongoDB" , "type" : "database" , "count" : 1 , "info" : { "x" : 203 , "y" : 102}}
{ "_id" : { "$oid" : "4eb75882ba4d4fab62ee4d02"} , "case" : 7 , "name" : "MongoDB" , "type" : "database" , "count" : 1 , "info" : { "x" : 203 , "y" : 102}}
{ "_id" : { "$oid" : "4eb75882ba4d4fab62ee4d03"} , "case" : 8 , "name" : "MongoDB" , "type" : "database" , "count" : 1 , "info" : { "x" : 203 , "y" : 102}}
{ "_id" : { "$oid" : "4eb75882ba4d4fab62ee4d04"} , "case" : 9 , "name" : "MongoDB" , "type" : "database" , "count" : 1 , "info" : { "x" : 203 , "y" : 102}}
start remove all
done
start insert :
Insert End
Collections Find one:
{ "_id" : { "$oid" : "4eb75882ba4d4fab62ee4d05"} , "case" : 0 , "name" : "MongoDB" , "type" : "database" , "count" : 1 , "info" : { "x" : 203 , "y" : 102}}
Collections Find one end
start remove all
done
start insert :
Insert End
start  query
result case=5:{ "_id" : { "$oid" : "4eb75882ba4d4fab62ee4d14"} , "case" : 5 , "name" : "MongoDB" , "type" : "database" , "count" : 1 , "info" : { "x" : 203 , "y" : 102}}
end  query
case >5:{ "_id" : { "$oid" : "4eb75882ba4d4fab62ee4d15"} , "case" : 6 , "name" : "MongoDB" , "type" : "database" , "count" : 1 , "info" : { "x" : 203 , "y" : 102}}
case >5:{ "_id" : { "$oid" : "4eb75882ba4d4fab62ee4d16"} , "case" : 7 , "name" : "MongoDB" , "type" : "database" , "count" : 1 , "info" : { "x" : 203 , "y" : 102}}
case >5:{ "_id" : { "$oid" : "4eb75882ba4d4fab62ee4d17"} , "case" : 8 , "name" : "MongoDB" , "type" : "database" , "count" : 1 , "info" : { "x" : 203 , "y" : 102}}
case >5:{ "_id" : { "$oid" : "4eb75882ba4d4fab62ee4d18"} , "case" : 9 , "name" : "MongoDB" , "type" : "database" , "count" : 1 , "info" : { "x" : 203 , "y" : 102}}
start remove all
done
start insert :
Insert End
Index Info:{ "v" : 1 , "key" : { "_id" : 1} , "ns" : "test.things" , "name" : "_id_"}
Index Info:{ "v" : 1 , "key" : { "case" : 1} , "ns" : "test.things" , "name" : "case_1"}
Index Info:{ "v" : 1 , "key" : { "case" : -1} , "ns" : "test.things" , "name" : "case_-1"}
start remove all
done

 

 

6 Morphia

Java的OOP特性,决定Java使用mongo的时候无可避免的要使用到ORM特性。

Morphia 是当前几个支持MongoDb ORm的比较好用的一个。

项目地址  http://code.google.com/p/morphia/

下载地址 暂时最高版本 0.98

http://code.google.com/p/morphia/downloads/list

 

 

不废话,上Sample

import java.net.UnknownHostException;

import com.google.code.morphia.Datastore;
import com.google.code.morphia.Morphia;
import com.google.code.morphia.query.Query;
import com.google.code.morphia.query.UpdateOperations;
import com.mongodb.DB;
import com.mongodb.Mongo;
import com.mongodb.MongoException;

public class MorphiaTest {

	// main
	//

	public static void main(String[] args) {
		try {
			Mongo m = new Mongo("localhost");
			DB db = m.getDB("test");
			Morphia morphia = new Morphia();
			morphia.map(Hotel.class).map(Address.class);

			Datastore ds = morphia.createDatastore(m, "test");

			Hotel hotel = new Hotel();
			hotel.setName("My Hotel123");
			// hotel.setId(new ObjectId("4ea510c8b24d395248f1f97f"));
			hotel.setStars(90);
			Address address = new Address();
			address.setStreet("123 Some street");
			address.setCity("Some city");
			address.setPostCode("123 456");
			address.setCountry("2Some country");
			// set address
			hotel.setAddress(address);
			// Save the POJO
			ds.save(hotel);
			// System.out.println(ds.find(Hotel.class, "stars >", 3));
			Query q = ds.createQuery(Hotel.class).disableValidation()
					.disableValidation();
			System.out.println(q.filter("id =", "4eb79c8cba4d913746120ae9").asList());
			// delete POJO
			ds.delete(q);
			// update operation
			ds.save(hotel);
			UpdateOperations<Hotel> ops = ds.createUpdateOperations(
					Hotel.class).set("name", "New Name1");
			ds.update(q, ops);
		} catch (UnknownHostException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (MongoException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
}

 

 利用 Morphia  可以使用Mongo DB,集成到项目 的DAO

里面。最小成本地使用Nosql技术,满足实际的项目需求。

 

 

本文大多使用原官网的code作为例子。只作为入门参考,即使这不是一个很好的教程。

你可能感兴趣的:(mongodb)