מדריך לדוגמא של CRUD ב-Java עבור MongoDB

ברוך הבא למדריך לדוגמאות ב-Java של MongoDB. לפני כן, למדנו איך להתקין את MongoDB במכונות Unix וביצענו כמה פקודות מהטרמינל. היום נתעקוב אחרי תכונות נהג Java של MongoDB ואיך לבצע פעולות נפוצות של CRUD (יצירה, קריאה, עדכון, מחיקה).

MongoDB Java

  1. הורדת נהג Java של MongoDB

  2. יצירת חיבור Java של MongoDB

  3. חיבור למסד נתונים של MongoDB

  4. MongoDB ואוספים

  5. דוגמה ב-Java של MongoDB

  6. הורדת מנהל Java של MongoDB

    אם יש לך פרויקט Maven, פשוט הוסף את התלות הבאה כדי לכלול את מנהל ה-Java של MongoDB ביישום שלך.

    <dependency>
    	<groupId>org.mongodb</groupId>
    	<artifactId>mongo-java-driver</artifactId>
    	<version>2.12.3</version>
    </dependency>
    

    אם יש לך פרויקט עצמאי, תוכל להוריד את מנהל ה-Java של MongoDB מקישור">כאן ולכלול אותו בנתיב הבנייה של הפרויקט שלך. כעת נעבור דרך כמה שימושים בסיסיים של מנהל ה-Java של MongoDB ואז נסתכל על דוגמה לתוכנית Java של MongoDB לפעולות CRUD.

  7. יצירת חיבור MongoDB ב-Java

    MongoClient הוא הממשק בין התוכנה שלנו ב-Java ובין שרת MongoDB. MongoClient משמש ליצירת חיבור, התחברות למסד נתונים, קבלת שמות אוספים ויצירה/קריאה/עדכון/מחיקה של מסד נתונים, אוספים, מסמכים ועוד. יתרון אחד של דרייבר Java של MongoDB שאני אוהב הוא שהוא thread safe, כלומר אנו יכולים ליצור מופע של MongoClient פעם אחת ולהשתמש בו שוב. אפילו אם כמה תהליכים יגששו אליו בו זמנית, חיבור יוחזר מברכת החיבור הפנימית שמתווכת על ידיו. לכל בקשה למסד הנתונים (חיפוש, הכנסה וכו') התהליך ב-Java יקבל חיבור ממערך החיבורים, יבצע את הפעולה וישחרר את החיבור. זה אומר שהחיבור (קצה החיבור) שנעשה בו שימוש יכול להיות שונה בכל פעם. להלן כמה מהשיטות הנפוצות להתחבר לשרת MongoDB.

    MongoClient mongoClient = new MongoClient(); // מתחבר למארח וליפרט ברירת מחדל, כלומר 127.0.0.1:27017
    // או
    MongoClient mongoClient = new MongoClient("localhost"); // מתחבר ליפרט ברירת מחדל, כלומר 27017
    // או
    MongoClient mongoClient = new MongoClient("localhost", 27017); // תמיד יש להשתמש בזה
    
    // או, להתחבר לקבוצת שירותים רשומים, עם גילוי אוטומטי של העיקרי
    MongoClient mongoClient = new MongoClient(Arrays.asList(new ServerAddress("localhost", 27017),
                                          new ServerAddress("localhost", 27018),
                                          new ServerAddress("localhost", 27019)));
    
  8. חיבור למסד נתונים של MongoDB

    פעם שאנו מקבלים את החיבור לשרת MongoDB, השלב הבא הוא ליצור חיבור למסד הנתונים, כפי שמוצג למטה. שימו לב שאם המסד עדיין לא קיים, MongoDB תיצור אותו בשבילך.

    MongoClient mongo = new MongoClient("localhost", 27017);
    DB db = mongo.getDB("journaldev");
    

    ‏MongoClient מספק שיטה שימושית לקבלת כל שמות מסדי הנתונים, כפי שמוצג למטה.

    MongoClient mongo = new MongoClient("localhost", 27017);
    List<String> dbs = mongo.getDatabaseNames();
    System.out.println(dbs); // [journaldev, local, admin]
    

    ניתן להשתמש באימות מבוסס שם משתמש-סיסמה עבור מסדי נתונים, במקרה כזה עלינו לספק פרטי אימות כמו שמוצג למטה.

    MongoCredential journaldevAuth = MongoCredential.createPlainCredential("pankaj", "journaldev", "pankaj123".toCharArray());
    MongoCredential testAuth = MongoCredential.createPlainCredential("pankaj", "test", "pankaj123".toCharArray());
    List<MongoCredential> auths = new ArrayList<MongoCredential>();
    auths.add(journaldevAuth);
    auths.add(testAuth);
    
    ServerAddress serverAddress = new ServerAddress("localhost", 27017);
    MongoClient mongo = new MongoClient(serverAddress, auths);
    

    אם אתה משתמש בגרסאות ישנות יותר, עליך לספק פרטי אימות לאחר קבלת אובייקט מסד הנתונים כמו שמוצג למטה.

    MongoClient mongo = new MongoClient("localhost", 27017);
    DB db = mongo.getDB("journaldev");
    boolean auth = db.authenticate("pankaj", "pankaj123".toCharArray());
    

    אתה יכול לזהות בקלות חסרונות בגישה הקודמת, האימות צריך להתבצע בשלב מוקדם מאוד מאחר ואין לנו אפשרות לשחזר אותו. אנו יכולים למחוק מסד נתונים באמצעות השיטה dropDatabase(String db) של MongoClient או באמצעות השיטה dropDatabase() של DB. מאחר ואנו מוחקים את מסד הנתונים, אני מעדיף להשתמש בשיטת MongoClient.

  9. MongoDB ואוספים

    כל מסד נתונים יכול להכיל אפס או מספר רב של אוספים, הם דומים לטבלאות בשרתי מסדי נתונים רלציוניים אך ללא תבנית ספציפית של הנתונים. חשוב לחשוב על זה כמו רשימה גנרית נגד רשימת מחרוזות בשפת תכנות ג'אווה. ניתן לקבל את כל שמות האוספים באמצעות הקוד הבא.

    MongoClient mongo = new MongoClient("localhost", 27017);
    DB db = mongo.getDB("journaldev");
    		
    Set<String> collections = db.getCollectionNames();
    System.out.println(collections); // [datas, names, system.indexes, users]
    

    ניתן לקבל אוסף מסוים על ידי הזנת שמו, כפי שמוצג למטה.

    DB db = mongo.getDB("journaldev");	
    DBCollection col = db.getCollection("users");
    

    שוב, אם האוסף לא קיים, MongoDB תיצור אותו עבורך. כל הנתונים ב-MongoDB נכנסים לתוך אוסף מסוים, לכן בנקודה זו אנו מוכנים לבצע פעולות הכנסה/עדכון/מחיקה. ניתן להשתמש בשיטת drop() ב-DBCollection כדי למחוק אוסף מהמסד נתונים.

  10. דוגמא ל-Java של MongoDB

Even though we can work on any valid JSON document in MongoDB collection, in real life we have POJO classes that are mapped with these data. So I will create a java bean and use it for my examples. `User.java`

```
package com.journaldev.mongodb.model;

public class User {

	private int id;
	private String name;
	private String role;
	private boolean isEmployee;
	
	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 String getRole() {
		return role;
	}
	public void setRole(String role) {
		this.role = role;
	}
	public boolean isEmployee() {
		return isEmployee;
	}
	public void setEmployee(boolean isEmployee) {
		this.isEmployee = isEmployee;
	}
}
```

Here is the complete MongoDB java example program showing all the CRUD operations one by one. `MongoDBExample.java`

```
package com.journaldev.mongodb.main;

import java.net.UnknownHostException;

import com.journaldev.mongodb.model.User;
import com.mongodb.BasicDBObjectBuilder;
import com.mongodb.DB;
import com.mongodb.DBCollection;
import com.mongodb.DBCursor;
import com.mongodb.DBObject;
import com.mongodb.MongoClient;
import com.mongodb.WriteResult;

public class MongoDBExample {

	public static void main(String[] args) throws UnknownHostException {
	
		User user = createUser();
		DBObject doc = createDBObject(user);
		
		MongoClient mongo = new MongoClient("localhost", 27017);
		DB db = mongo.getDB("journaldev");
		
		DBCollection col = db.getCollection("users");
		
		//יצירת משתמש
		WriteResult result = col.insert(doc);
		System.out.println(result.getUpsertedId());
		System.out.println(result.getN());
		System.out.println(result.isUpdateOfExisting());
		System.out.println(result.getLastConcern());
		
		//דוגמא לקריאה
		DBObject query = BasicDBObjectBuilder.start().add("_id", user.getId()).get();
		DBCursor cursor = col.find(query);
		while(cursor.hasNext()){
			System.out.println(cursor.next());
		}
		
		//דוגמא לעדכון
		user.setName("Pankaj Kumar");
		doc = createDBObject(user);
		result = col.update(query, doc);
		System.out.println(result.getUpsertedId());
		System.out.println(result.getN());
		System.out.println(result.isUpdateOfExisting());
		System.out.println(result.getLastConcern());
		
		//דוגמא למחיקה
		result = col.remove(query);
		System.out.println(result.getUpsertedId());
		System.out.println(result.getN());
		System.out.println(result.isUpdateOfExisting());
		System.out.println(result.getLastConcern());
		
		//סגירת משאבים
		mongo.close();
	}

	private static DBObject createDBObject(User user) {
		BasicDBObjectBuilder docBuilder = BasicDBObjectBuilder.start();
								
		docBuilder.append("_id", user.getId());
		docBuilder.append("name", user.getName());
		docBuilder.append("role", user.getRole());
		docBuilder.append("isEmployee", user.isEmployee());
		return docBuilder.get();
	}

	private static User createUser() {
		User u = new User();
		u.setId(2);
		u.setName("Pankaj");
		u.setEmployee(true);
		u.setRole("CEO");
		return u;
	}
	
	

}
```

A sample execution results in following output.

```
null
0
false
WriteConcern { "getlasterror" : 1} / (Continue on error? false)
{ "_id" : 2 , "name" : "Pankaj" , "role" : "CEO" , "isEmployee" : true}
null
1
true
WriteConcern { "getlasterror" : 1} / (Continue on error? false)
null
1
false
WriteConcern { "getlasterror" : 1} / (Continue on error? false)
```

Notice that I am saving User id with **\_id** name, this is a reserved key for the primary key of any record in the collection. If we don't provide one, MongoDB will create one for us. It's like sequencer or auto increment column in relational database tables. Since I am deleting the created record, further execution won't cause any issues. But if there are duplicate record, then we will get below errors.

```
Exception in thread "main" com.mongodb.MongoException$DuplicateKey: { "serverUsed" : "localhost:27017" , "ok" : 1 , "n" : 0 ,
 "err" : "insertDocument :: caused by :: 11000 E11000 duplicate key error index: journaldev.users.$_id_  dup key: { : 1 }" , 
"code" : 11000}
	at com.mongodb.CommandResult.getWriteException(CommandResult.java:88)
	at com.mongodb.CommandResult.getException(CommandResult.java:79)
	at com.mongodb.DBCollectionImpl.translateBulkWriteException(DBCollectionImpl.java:314)
	at com.mongodb.DBCollectionImpl.insert(DBCollectionImpl.java:189)
	at com.mongodb.DBCollectionImpl.insert(DBCollectionImpl.java:165)
	at com.mongodb.DBCollection.insert(DBCollection.java:93)
	at com.mongodb.DBCollection.insert(DBCollection.java:78)
	at com.mongodb.DBCollection.insert(DBCollection.java:120)
	at com.journaldev.mongodb.main.MongoDBExample.main(MongoDBExample.java:27)
```

זהו, אתה מוכן להתחיל עם נהג Java של MongoDB, נבחן יותר תכונות בפוסטים הבאים.

Source:
https://www.digitalocean.com/community/tutorials/mongodb-java-crud-example-tutorial