MongoDB学习03之JAVA简单操作增删改查

       经过前面几篇博文的学习,对MongoDB已经有一定的了解了,现在用JAVA来操作MongoDB,进行一些简单的增删改查,查询有复杂查询,这里不一一列举,同学自己看看API就OK了。

      MongoDB JAVA驱动下载:https://github.com/mongodb/mongo-java-driver/downloads


Student.java

package com.fei;

public class Student {

	private int id;
	private String name;
	private int age;
	private int height;
	
	public Student() {
		
	}
	
	public Student(int id, String name, int age, int height) {
		super();
		this.id = id;
		this.name = name;
		this.age = age;
		this.height = height;
	}
	public int getId() {
		return id;
	}
	public void setId(int id) {
		this.id = id;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public int getAge() {
		return age;
	}
	public void setAge(int age) {
		this.age = age;
	}
	public int getHeight() {
		return height;
	}
	public void setHeight(int height) {
		this.height = height;
	}
	
	public String toString(){
		return "student["+"id="+id+",name="+name+",age="+age+",height="+height+"]";
	}
}
MongoDBUtil.java

package com.fei;

import java.net.UnknownHostException;

import com.mongodb.DB;
import com.mongodb.DBCollection;
import com.mongodb.Mongo;

public class MongoDBUtil {

	private final static String IP = "127.0.0.1";
	private final static int PORT = 27017;
	private final static String DBNAME = "school";
	
	private   Mongo mg = null;
	private   DB db = null;
	private  DBCollection  collection= null;
	
	private MongoDBUtil(){};
	
	public static MongoDBUtil getInstance(){
		return new MongoDBUtil();
	}
	
	
	public DBCollection getDBConllection(String collectionName){
		init();
		collection = db.getCollection(collectionName);
		return collection;
	}
	private  void init(){
		try {
			mg = new Mongo(IP,PORT);
		} catch (UnknownHostException e) {
			e.printStackTrace();
			throw new RuntimeException("mongo连接失败!");
		}
		db = mg.getDB(DBNAME);
		
	}
	public  void destory(){
		if(mg != null)
			mg.close();
		db = null;
		collection = null;
	}
}

StudentDaoImpl.java

package com.fei;

import java.util.ArrayList;
import java.util.List;

import com.mongodb.BasicDBObject;
import com.mongodb.DBCollection;
import com.mongodb.DBCursor;
import com.mongodb.DBObject;

public class StudentDaoImpl {

	private final static String COLLECTION_NAME = "student";
	private final static String[] FIELDS = new String[]{"_id","name","age","height"};
	private MongoDBUtil dbUtil = null;
	
	public List<Student> queryAll(){
		List<Student> students = new  ArrayList<Student>();
		DBCollection collection = getDBCollection();
		DBCursor cursor = collection.find();
		while(cursor.hasNext()){
			DBObject dbObject = cursor.next();
			students.add(convert(dbObject));
		}
		destory();
		return students;
	}
	
    public void add(Student s){
    	DBObject o = new BasicDBObject();
    	o.put(FIELDS[0],s.getId());
    	o.put(FIELDS[1], s.getName());
    	o.put(FIELDS[2], s.getAge());
    	o.put(FIELDS[3], s.getHeight());
    	
    	DBCollection collection = getDBCollection();
    	//insert 与 save的区别,如果_id已存在,使用insert会报错,使用save,则新的替换旧的
    //	collection.insert(o);
    	collection.save(o);
    	destory();
    }
	public void update(Student s){
		DBObject q = new BasicDBObject();
		q.put(FIELDS[0],s.getId());
		
		DBObject o = new BasicDBObject();
    	o.put(FIELDS[1], s.getName());
    	o.put(FIELDS[2], s.getAge());
    	o.put(FIELDS[3], s.getHeight());
    	
    	DBCollection collection = getDBCollection();
    	collection.update(q, o);
    	destory();
	}
    public void remove(int id){
    	DBCollection collection = getDBCollection();
    	DBObject o = new BasicDBObject();
    	o.put(FIELDS[0], id);
    	collection.remove(o);
    	destory();
    }
    
    private DBCollection getDBCollection(){
    	if(dbUtil == null){
    		dbUtil = MongoDBUtil.getInstance();
    	}
    	return dbUtil.getDBConllection(COLLECTION_NAME);
    }
	private Student convert(DBObject dbObject){
		if(! isStudent(dbObject)){
			return null;
		}
		Student s = new Student();
		s.setId(Double.valueOf(dbObject.get(FIELDS[0]).toString()).intValue());
		s.setName(dbObject.get(FIELDS[1]).toString());
		s.setAge(Double.valueOf(dbObject.get(FIELDS[2]).toString()).intValue());
		s.setHeight(Double.valueOf(dbObject.get(FIELDS[3]).toString()).intValue());
		return s;
	}
	
	private boolean isStudent(DBObject dbObject){
		for(String field : FIELDS){
			if(! dbObject.containsField(field)){
				return false;
			}
		}
		return true;
	}
	private void destory(){
		if(dbUtil != null)
			dbUtil.destory();
	}
}

dbData.txt

use school;
db.createCollection('student');

db.student.insert({'_id':1,'name':'貂蝉','age':16,'height':160});
db.student.insert({'_id':2,'name':'蔡琰','age':17,'height':165});
db.student.insert({'_id':3,'name':'甄宓','age':13,'height':155});
db.student.insert({'_id':4,'name':'孙尚香','age':15,'height':160});

MongoDBTest.java

package com.fei;


public class MongoDBTest {

	private static StudentDaoImpl dao = new StudentDaoImpl();
	public static void main(String[] args) {
		queryAll();
		
		Student s = new Student(10,"赵飞燕",16,170);
		add(s);
		queryAll();
		
		s.setAge(15);
		s.setHeight(165);
		update(s);
		queryAll();
		
		remove(10);
		queryAll();
	}
	
	private static void queryAll(){
		System.out.println("=======查询全部学生========");
		for(Student s : dao.queryAll()){
			System.out.println(s);
		}
	}
	
	private static void add(Student s){
		System.out.println("=======新增学生========");
		System.out.println(s);
		dao.add(s);
	}
	private static void update(Student s){
		System.out.println("=======修改学生=======");
		System.out.println(s);
		dao.update(s);
	}
	private static void remove(int id){
		System.out.println("=======删除学生=====");
		System.out.println("学生id="+id);
		dao.remove(id);
	}
}

运行结果图:




源代码下载





  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值