1. 程式人生 > >MongoDB3.0+資料操作工具封裝

MongoDB3.0+資料操作工具封裝

該文章只適合於初學者,裡面的程式碼很簡單,也多需要優化完善的地方,就是為了讓初學者少走彎路,起到借鑑的作用。

需要引用的包:

<span style="white-space:pre">		</span><dependency>
			<groupId>junit</groupId>
			<artifactId>junit</artifactId>
			<version>4.8.1</version>
			<scope>test</scope>
		</dependency>
		<dependency>
			<groupId>org.jmock</groupId>
			<artifactId>jmock-junit4</artifactId>
			<version>2.8.1</version>
		</dependency>
		<dependency>
			<groupId>org.jmock</groupId>
			<artifactId>jmock</artifactId>
			<version>2.8.1</version>
		</dependency>
		<dependency>
			<groupId>org.jmock</groupId>
			<artifactId>jmock-legacy</artifactId>
			<version>2.8.1</version>
		</dependency>
		<dependency>
			<groupId>org.mongodb</groupId>
			<artifactId>mongo-java-driver</artifactId>
			<version>3.1.0</version>
		</dependency>


首先,我們拿一個使用者來進行操作:

1建立一個User實體物件:

public class User {
	private String name = null;
    
    private int age = -1;
     
    private int updateTimes = -1;
 
    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 getUpdateTimes()
    {
        return updateTimes;
    }
 
    public void setUpdateTimes(int updateTimes)
    {
        this.updateTimes = updateTimes;
    }
 
    @Override
    public String toString()
    {
        return "User [name=" + name + ", age=" + age + ", updateTimes=" + updateTimes + "]";
    }
 
    public Document toBasicDBObject()
    {
        Document user = new Document();
        user.put("name", this.name);
        user.put("age", this.age);
        user.put("updateTimes", this.updateTimes);
        return user;
    }
}

2接著,建立一個工具類,讓來連線MongoDB資料庫:
public final class MongoDBUtil 
{
   private static MongoClient mongoClient = null;
   private static MongoDatabase database = null;
   private static ServerAddress serverAddress = null;
   private static MongoCredential  credentials  = null;
   private static List<ServerAddress> addressLists =new ArrayList<ServerAddress>();
   private static List<MongoCredential> credentialsLists = new ArrayList<MongoCredential>();

   public static void init(){
	   try{
	   //mongoClient = new MongoClient("192.168.32.129",27017);
	   serverAddress = new ServerAddress("192.168.32.129",27017);
	   addressLists.add(serverAddress);
	   //credentials = MongoCredential.createCredential("test1", "test", "test1".toCharArray());
	   credentials = MongoCredential.createMongoCRCredential("test1", "test", "test1".toCharArray());
	   credentialsLists.add(credentials);
	   mongoClient = new MongoClient(addressLists, credentialsLists);
	   }catch (MongoException e)
       {
           System.out.println(e.toString());
       }
	   if(null != mongoClient){
		   database = mongoClient.getDatabase("test");
	   }
	 
   }
   public static MongoClient getMongoClient()
   {
       if (null == mongoClient)
       {
           init();
       }
        
       return mongoClient;
   }
   /**
    * 獲取database
    * @return
    */
	public static MongoDatabase getDatabase() {
		if(null == mongoClient){
			init();
		}
		return database;
	}
	/**
	 * 獲取User Collection
	 * @return
	 */
	public static MongoCollection<Document> getUserCollection(){
		if(null == database){
			database = getDatabase();
		}
		if(null != database){
			return database.getCollection("data");
		}
		return null;
	}
	/**
	 * 刪除所有使用者
	 */
	public static void deleteAllUsers(){
		System.out.println("刪除User Collection中所有資料...");
		MongoCollection<Document> collection = getUserCollection();

		FindIterable<Document> cursor = collection.find();
		while(cursor.iterator().hasNext()){
			collection.deleteOne(cursor.iterator().next());
		}
		System.out.println("====================================");
	}
	/**
	 * 查詢所有使用者
	 */
	public static void queryAllUsers(){
		System.out.println("查詢User Collection中所有資料:");
		 
        MongoCollection<Document> collection = getUserCollection();
         
        //方法一
        /*MongoCursor<Document> cur = collection.find().iterator();
        try{
        	 while (cur.hasNext())
             {
                 System.out.println(cur.next().toJson());
             }
        }catch(Exception e){
        	System.out.println(e.getMessage()+e);
        }finally {
        	cur.close();
		}*/
       //方法二
        for (Document  cursor : collection.find()) {
			System.out.println(cursor.toJson());
		}
         
        System.out.println("================================================================");
	}
	
	/**
	 * 儲存使用者資訊
	 * @param user
	 */
	public static void saveUser(User user){
		System.out.println("儲存使用者資訊:" + user.toString());
        MongoCollection<Document> userCollection = getUserCollection();
        userCollection.insertOne(user.toBasicDBObject());
        System.out.println("================================================================");
    
	}
	
	/**
     * 更新使用者資訊
     * @param user
     */
    public static void update(User user)
    {
        System.out.println("更新使用者資訊:" + user.toString());
        MongoCollection<Document> userCollection = getUserCollection();
        userCollection.updateMany(new Document().append("name", user.getName()), user.toBasicDBObject());
        System.out.println("================================================================");
    }
     
    /**
     * 增加使用者更新次數
     * @param userName 使用者名稱
     */
    public static void incUserUpdateTimes(String userName)
    {
    	MongoCollection<Document> userCollection = getUserCollection();
        BasicDBObject newDocument =new BasicDBObject().append("$inc", new BasicDBObject().append("updateTimes", 1));
        userCollection.updateOne(new BasicDBObject().append("name", userName), newDocument);
    }
     
    /**
     * 更新使用者名稱
     * @param oldName 舊使用者名稱
     * @param newName 新使用者名稱
     */
    public static void updateUserName(String oldName, String newName)
    {
    	MongoCollection<Document> userCollection = getUserCollection();
        BasicDBObject newDocument =new BasicDBObject().append("$set", new BasicDBObject().append("name", newName));
        userCollection.updateOne(new BasicDBObject().append("name", oldName), newDocument);
    }
     
    /**
     * 更新User Age
     * @param userName 使用者名稱
     * @param age Age
     */
    public static void updateUserAge(String userName, int age)
    {
        MongoCollection<Document> userCollection = getUserCollection();
        BasicDBObject newDocument =new BasicDBObject().append("$set", new BasicDBObject().append("age", age));
        userCollection.updateOne(new BasicDBObject().append("name", userName), newDocument);
    }
     
     
    public static User queryUserByName(String userName)
    {
        MongoCollection<Document> userCollection = getUserCollection();
        BasicDBObject query =new BasicDBObject();
        query.put("name", userName);
        User user = null;
        for (Document  cursor : userCollection.find(query)) {
			System.out.println(cursor.toJson());
			Map<String, Object> userMap = (Map<String, Object>) cursor;
            
            user = new User();
            user.setName(String.valueOf(userMap.get("name")));
            user.setAge(Integer.valueOf(String.valueOf(userMap.get("age"))));
            user.setUpdateTimes(Integer.valueOf(String.valueOf(userMap.get("updateTimes"))));
             
            System.out.println(user.toString());
		} 
        /*MongoCursor<Document> cursor = userCollection.find(query).iterator();
        while(cursor.hasNext())
        {
            Document document = cursor.next();

            Map<String, Object> userMap = (Map<String, Object>) document;
             
            user = new User();
            user.setName(String.valueOf(userMap.get("name")));
            user.setAge(Integer.valueOf(String.valueOf(userMap.get("age"))));
            user.setUpdateTimes(Integer.valueOf(String.valueOf(userMap.get("updateTimes"))));
             
            System.out.println(user.toString());
        }*/
         
        return user;
    }
     
    public static void queryUserByAge(List<Integer> ageList)
    {
    	MongoCollection<Document> userCollection = getUserCollection();
        BasicDBObject query =new BasicDBObject();
        query.put("age", new BasicDBObject("$in", ageList));
        FindIterable<Document> cursor = userCollection.find(query);
        while(cursor.iterator().hasNext())
        {
            System.out.println(cursor.iterator().next());
        }
    }
     
    public static void queryUserByGreatThanAge(int age)
    {
    	MongoCollection<Document> userCollection = getUserCollection();
        BasicDBObject query =new BasicDBObject();
        query.put("age", new BasicDBObject("$gt", age));
        FindIterable<Document> cursor = userCollection.find(query);
        while(cursor.iterator().hasNext())
        {
            System.out.println(cursor.iterator().next());
        }
    }
     
    public static void queryUserByLessThanAge(int age)
    {
    	MongoCollection<Document> userCollection = getUserCollection();
        BasicDBObject query =new BasicDBObject();
        query.put("age", new BasicDBObject("$lt", age));
        FindIterable<Document> cursor = userCollection.find(query);
        while(cursor.iterator().hasNext())
        {
            System.out.println(cursor.iterator().next());
        }
    }
     
    public static void queryUserNotEquireAge(int age)
    {
    	MongoCollection<Document> userCollection = getUserCollection();
        BasicDBObject query =new BasicDBObject();
        query.put("age", new BasicDBObject("$ne", age));
        FindIterable<Document> cursor = userCollection.find(query);
        while(cursor.iterator().hasNext())
        {
            System.out.println(cursor.iterator().next());
        }
    }
     
    public static void deleteUserByName(String userName)
    {
    	MongoCollection<Document> userCollection = getUserCollection();
        BasicDBObject document =new BasicDBObject();
        document.put("name", userName);
        userCollection.deleteMany(document);
    }
     
    public static void deleteUserByNameList(List<String> nameList)
    {
    	MongoCollection<Document> userCollection = getUserCollection();
        BasicDBObject query =new BasicDBObject();
        query.put("name", new BasicDBObject("$in", nameList));
        userCollection.deleteMany(query);
    }
     
	
	public static void setDatabase(MongoDatabase database) {
		MongoDBUtil.database = database;
	}
  
}
注意:該工具中只有下面單元測試中的幾個方法是成功測試的,其他的還需要自己下面測試,應該也是沒問題的。

3最後,單元測試看看效果,是否真的可行:

public class MongoDBTest
{
    public static void main(String[] args) {
    	System.out.println("================================================================");
    	// 查詢所有的Database
    	MongoClient mongoClient = MongoDBUtil.getMongoClient();
    	System.out.println("查詢MongoDB中存在的所有資料庫:");
	    for (ServerAddress name : mongoClient.getAllAddress()) {
	    	System.out.println("dbName: " + name);
		}
		// 查詢DB中所有的Collection(可以理解為像關係型資料庫中的Table)
	    MongoDatabase database = MongoDBUtil.getDatabase();
	    System.out.println("abd="+database.getCollection("abc").toString());
	    MongoCollection<Document> collection = null;
	    List<Document> foundDocument = null;
	    collection = database.getCollection("person");
		   foundDocument = collection.find().into(
				    new ArrayList<Document>());
		   System.out.println(foundDocument);
    }
    
    @Test
    public void addUsers(){
    	for(int i=0;i<20000;i++){
    		User user = new User();
    		user.setName("user" + i);
    		user.setAge(2);
    		user.setUpdateTimes(0);
    		//儲存使用者資訊
    		MongoDBUtil.saveUser(user);
    		System.out.println("------------"+i);
    	}
    }
    
    @Test
    public void deleteAllUsers(){
    	MongoDBUtil.deleteAllUsers();
    }
    
    @Test
    public void queryAllUsers(){
    	MongoDBUtil.queryAllUsers();
    }
    
    @Test
    public void updateUser(){
    	User user = new User();
    	user.setName("user19999");
    	user.setAge(39);
    	user.setUpdateTimes(3);
    	MongoDBUtil.update(user);
    }
    
    @Test
    public void queryUserByName(){
    	MongoDBUtil.queryUserByName("user19999");
    }
}

這裡,就完了,希望不要吐槽微笑