Juntiger
MongoDB와 JAVA 연동하기 본문
MongoDB와 Java를 연동해보자.
이클립스를 사용했다. 이클립스와 MongoDB를 연동하기 위해 드라이버를 다운받아햐 한다.
드라이버는 여기서 다운받는다. 현재 (2016년 6월 9일) 최신 버전은 2.14.2
파란색 체크 표시된 파일 두 개를 다운 받는다. sources 파일은 ctrl을 눌렀을 때 api를 보기위한 파일이다.
라이브러리를 추가하기 위해서 프로젝트를 마우스 왼쪽 클릭한 후 alt + enter를 누른다.
그 다음 Java Build Path > Libraries > Add external JARs를 눌러서 mongo-java-driver-2.14.2.jar 를 추가한다.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 | import com.mongodb.BasicDBObject; import com.mongodb.DB; import com.mongodb.DBCollection; import com.mongodb.DBCursor; import com.mongodb.DBObject; import com.mongodb.MongoClient; import com.mongodb.MongoClientURI; import java.net.UnknownHostException; public class MongoDB { // Extra helper code //seedData가 document public static BasicDBObject[] createSeedData(){ BasicDBObject seventies = new BasicDBObject(); seventies.put("decade", "1970s"); seventies.put("artist", "Debby Boone"); seventies.put("song", "You Light Up My Life"); seventies.put("weeksAtOne", 10); BasicDBObject eighties = new BasicDBObject(); eighties.put("decade", "1980s"); eighties.put("artist", "Olivia Newton-John"); eighties.put("song", "Physical"); eighties.put("weeksAtOne", 10); BasicDBObject nineties = new BasicDBObject(); nineties.put("decade", "1990s"); nineties.put("artist", "Mariah Carey"); nineties.put("song", "One Sweet Day"); nineties.put("weeksAtOne", 16); final BasicDBObject[] seedData = {seventies, eighties, nineties}; return seedData; } public static void main(String[] args) throws UnknownHostException{ // Create seed data final BasicDBObject[] seedData = createSeedData(); // Standard URI format: mongodb://[dbuser:dbpassword@]host:port/dbname // uri 정보를 받아옴 MongoClientURI uri = new MongoClientURI("mongodb://youCanUseYourId:youCanUseYourPw@ds025263.mlab.com:25263/db_juntiger"); MongoClient client = new MongoClient(uri); DB db = client.getDB(uri.getDatabase()); /* * First we'll add a few songs. Nothing is required to create the * songs collection; it is created automatically when we insert. */ //getCollection - 자동으로 컬렉션을 만들어준다. DBCollection songs = db.getCollection("songs"); // Note that the insert method can take either an array or a document. //collection에 document를 넣음 songs.insert(seedData); /* * Then we need to give Boyz II Men credit for their contribution to * the hit "One Sweet Day". */ //The $set operator replaces the value of a field with the specified value. BasicDBObject updateQuery = new BasicDBObject("song", "One Sweet Day"); //$set 오퍼레이터는 artist를 바꾸기 위해 사용 //artist를 "Mariah Carey ft. Boyz II Men"로 바꾸겠다는 말 songs.update(updateQuery, new BasicDBObject("$set", new BasicDBObject("artist", "Mariah Carey ft. Boyz II Men"))); /* * Finally we run a query which returns all the hits that spent 10 * or more weeks at number 1. */ //gte는 greater than or equal 을 의미. 크거나 같은. >= BasicDBObject findQuery = new BasicDBObject("weeksAtOne", new BasicDBObject("$gte",10)); //1은 오른차순, -1은 내림차순 decade 필드를 오름차순으로 정렬함 BasicDBObject orderBy = new BasicDBObject("decade", 1); DBCursor docs = songs.find(findQuery).sort(orderBy); while(docs.hasNext()){ DBObject doc = docs.next(); System.out.println( "In the " + doc.get("decade") + ", " + doc.get("song") + " by " + doc.get("artist") + " topped the charts for " + doc.get("weeksAtOne") + " straight weeks." ); } // Since this is an example, we'll clean up after ourselves. songs.drop(); // Only close the connection when your app is terminating client.close(); } } |
코드 출처 - https://github.com/mongolab/mongodb-driver-examples/blob/master/java/JavaSimpleExample.java
이해가 안가는 부분이 있어서 API 문서도 들여다 보고 구글링도 해서 한글로 주석을 몇 개 달아 놓았다.
songs.drop()에 주석 처리를 해주면 데이터가 정상적으로 삽입된다.
응용해서 콘솔창에서 데이터를 입력하면 데이터베이스에 저장되게 만들 수도 있다.
'JAVA' 카테고리의 다른 글
MongoDB와 JAVA 연동하기 (2) (1) | 2016.06.11 |
---|
Comments