日期:2014-05-16  浏览次数:20480 次

java使用morphia链接mogon数据库
morphia是nosql的一种轻量级框架,在java应用中使用morphia连接数据库需要导入的包有:
log4j-1.2.14.jar
mongo-2.4.jar
morphia-0.99.jar
morphia-logging-slf4j-0.99.jar
morphia-validation-0.99.jar
slf4j-api-1.5.10.jar
slf4j-log4j12-1.5.10.jar
sli4j-core-2.0.jar
sli4j-slf4j-log4j-2.0.jar

启动mongo服务器 mongod --dbpath E:\data

写一个实体类:
@Entity(value="name",noClassnameStored=true)
public class MyEntity {

	@Id
	public ObjectId id;
	public String name;
}



写一个测试类:
	public static void main(String[] args) throws Exception{
		Morphia morphia = new Morphia();
		Mongo mongo = new Mongo("127.0.0.1",27017);
		Datastore ds = morphia.createDatastore(mongo, "mydb");
		// new Morphia().createDatastore("mydb");
		ds.ensureIndexes(); 
		ds.ensureCaps();
		
		MyEntity me = new MyEntity();
		me.name = "hsys";
		ds.save(me);
		MyEntity e3 = ds.find(MyEntity.class).get(); 
		UpdateOperations<MyEntity> ops = ds.createUpdateOperations(MyEntity.class).set("name", "淮少");
		//UpdateOperations<MyEntity> ops = ds.createUpdateOperations(MyEntity.class).unset("name");
		ds.update(ds.createQuery(MyEntity.class).field(Mapper.ID_KEY).equal(e3.id), ops);
		
		for(MyEntity me2 : ds.find(MyEntity.class)){
			System.out.println(me2.name);
		}
	}



关于morphia的详细介绍,请看官方文档:http://code.google.com/p/morphia/w/list

关于mongodb的介绍,请看官方文档:https://github.com/mongodb