MongoDB學習03之JAVA簡單操作增刪改查
阿新 • • 發佈:2018-12-24
經過前面幾篇博文的學習,對MongoDB已經有一定的瞭解了,現在用JAVA來操作MongoDB,進行一些簡單的增刪改查,查詢有複雜查詢,這裡不一一列舉,同學自己看看API就OK了。
MongoDB JAVA驅動下載:https://github.com/mongodb/mongo-java-driver/downloads
Student.java
MongoDBUtil.javapackage 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+"]"; } }
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);
}
}
執行結果圖: