Spring Data MongoDB 介紹

  • 2,522 views
Uploaded on

NoSQL Taiwan 分享 …

NoSQL Taiwan 分享
蘇國鈞 / Monster Supreme

More in: Technology
  • Full Name Full Name Comment goes here.
    Are you sure you want to
    Your message goes here
    Be the first to comment
No Downloads

Views

Total Views
2,522
On Slideshare
0
From Embeds
0
Number of Embeds
1

Actions

Shares
Downloads
46
Comments
0
Likes
4

Embeds 0

No embeds

Report content

Flagged as inappropriate Flag as inappropriate
Flag as inappropriate

Select your reason for flagging this presentation as inappropriate.

Cancel
    No notes for slide

Transcript

  • 1. .. Spring Data MongoDB 蘇國鈞 monster.kcsu@gmail.com http://www.facebook.com/monster.kcsu November 17, 2012
  • 2. . Profile 國立台灣大㈻電機工程㈻研究所畢業 現任 ㈾訊工業策進會 數位教育研究所 ㈾訊技術訓練㆗心 教㈻組長 在 Java 領域㈲㈩多年的講師教㈻經驗 熟悉 XML/Web Services、Design Patterns、EJB/JPA 等 Java EE 規格, Struts/Spring/Hibernate 等 Open Source Framework,與 JBoss AS、GlassFish 等 Application Server 目前負責雲端運算相關技術的推廣,主要包 括 Apache Hadoop、Google App Engine、 Microsoft Azure 等 Cloud Platform,與 iOS、Android、Windows Phone 等 Smart Handheld Device 端的整合運用
  • 3. . Outline . 1 MongoDB . 2 MongoDB Java Driver . 3 Spring Data MongoDB
  • 4. .1 MongoDB.2 MongoDB Java Driver.3 Spring Data MongoDB
  • 5. MongoDB. http://www.mongodb.org/ MongoDB: 2007 年 10gen 公司以 C/C++ 開發 GNU-AGPL 授權,也可以談其他授權方式 2009 年 11 ㈪推出 1.0 版 是 Document-Oriented Database 每個 Database 都是以檔案的型式存在 是㆒個比較㆒般化的 NoSQL 解決方案 希望結合 RDBMS 與 Key/Value Store ㊝點 盡量提供像 RDBMS 那麼強大的查詢功能 ㊜合用在 Web App、Internet 架構的環境 目前最新是 2012 年 10 ㈪ 的 2.2.1 版
  • 6. . RDBMS vs. MongoDB RDBMS MongoDB Database Database Table Collection Record/Row Document Column Field Primary Key _id
  • 7. . Document 1 { 2 _id: ObjectId(4bd9e8e17cefd644108961bb), 3 title: Adventures in Databases, 4 url: http://example.com/databases.txt, 5 author: msmith, 6 vote_count: 20, 7 created: Sat Oct 6 2012 14:36:58 GMT+0800 (PST) 8 9 tags: [databases, mongodb, indexing],1011 image:12 {13 url: http://example.com/db.jpg,14 caption: ,15 type: jpg,16 size: 75381,17 data: "Binary"18 }19 }
  • 8. . JavaScript Shell Shell: MongoDB 的 Client 端 互動方式不是透過熟悉的 SQL 而是 JavaScript 與㆒組簡單的 API Shell Command: help 與 exit show dbs 與 show collections use databaseName 新增:db.collectionName.insert(...) 刪除:db.collectionName.remove(...) 查詢:db.collectionName.find(...) 修改:db.collectionName.update(...)
  • 9. . JavaScript Shell Command 1 var obj = db.runCommand({geoNear: "zips", near: [-118.406477, 34.090107]}); 2 var results = obj.results; 3 var city = {}; 4 var dis = 0; 5 for (var i = 0 ; i < results.length ; i++) { 6 city = results[i].obj; 7 dis = results[i].dis; 8 print("City = " + city.city + " Distance = " + dis); 9 }
  • 10. . JavaScript Shell Output
  • 11. .1 MongoDB.2 MongoDB Java Driver.3 Spring Data MongoDB
  • 12. Java Driver. https://github.com/mongodb/mongo-java-driver/downloads MongoDB 的 Language Support,稱為 Driver: 主要的 Language mongodb.org 都㈲支援 ㈲㆒些 Language 則是由 Community 支援 Interface 盡量㈲相同的 Method Data Structure 盡量結合 Language ㈵性 Java Driver: 目前最新是 2012 年 10 ㈪出的 2.9.3 版 Wrapper:Morphia for Java
  • 13. Object/Document Mapping 方式. http://docs.mongodb.org/manual/tutorial/aggregation-examples/ 1 { 2 "city" : "BEVERLY HILLS", 3 "loc" : [ -118.406477, 34.090107 ], 4 "pop" : 20700, 5 "state" : "CA", 6 "_id" : "90210" 7 } 1 public class City implements Serializable { 2 private String city; 3 private double[] loc; 4 private int pop; 5 private String state; 6 private String id; 7 } 1 public class Location implements Serializable { 2 private double longitude; 3 private double latitude; 4 }
  • 14. . MongoDB Java Driver 連線建立方式 1 public class MongoDBUtils { 2 private static Mongo mongo = null; 3 4 static { 5 try { 6 mongo = new Mongo("localhost", 27017); 7 } 8 catch (UnknownHostException ex) { 9 System.out.println(ex.getMessage());10 }11 }1213 public static DB getDB(String dbName) {14 return mongo.getDB(dbName);15 }1617 public static DBCollection getCollection(String dbName, String colName) {18 return mongo.getDB(dbName).getCollection(colName);19 }20 }
  • 15. . MongoDB Java Driver ㈾料存取方式 1 public class CityFinder { 2 public static void main(String[] args) { 3 DBCollection collection = 4 MongoDBUtils.getCollection("cities", "zips"); 5 6 BasicDBObject doc = new BasicDBObject(); 7 doc.put("_id", "90210"); 8 doc = (BasicDBObject) collection.findOne(doc); 910 System.out.println(doc);1112 Gson gson = new Gson();13 City city = gson.fromJson(doc.toString(), City.class);1415 System.out.println("City = " + city.getCity());16 System.out.println("Longitude = " + city.getLoc()[0]);17 System.out.println("Latitude = " + city.getLoc()[1]);18 }19 }
  • 16. .1 MongoDB.2 MongoDB Java Driver.3 Spring Data MongoDB
  • 17. Spring Data. http://www.springsource.org/spring-data
  • 18. . Spring Data 希望能夠透過 Spring 整合重要的㈾料存取技術: 透過 Spring 存取 RDBMS、NoSQL、與 MapReduce Framework 基本㆖只是個技術統稱,每個 RDBMS/ NoSQL 的存取方式都不盡相同 目前 Spring Data 家族包括: Spring Data Hadoop Spring Data JPA Spring Data MongoDB Spring Data Neo4j …
  • 19. Spring Data MongoDB. http://www.springsource.org/spring-data/mongodb
  • 20. . Spring Data MongoDB 希望能夠透過 Spring 整合 MongoDB 這種 Document 型態的㈾料存取技術 提供高階的 Template 封裝對 Document 的 相關操作,跟 Spring 整合 JDBC 與 Hibernate 的方式很類似 可以整合 Spring 的 IoC 與 Data Access Exception Hierarchy 等功能,也可以直接使 用高階的 Template 支援 官方文件裡面也稱為 Spring Data Document 或 DATADOC
  • 21. . Spring Data MongoDB 系統需求 Java SE 6 MongoDB 1.6.5 2.2 版開始不支援 XP MongoDB Java Driver Spring Framework 3.0.x JCL (Apache/Jakarta Commons Logging) Spring Data Commons SLF4J SLF4J-JCL + JCL Spring Data MongoDB (Optional) Google GSON 或 Jackson 之類 的 JSON Processor
  • 22. . Spring Data MongoDB 主要功能 High-Level Template-Style Support MongoTemplate 與 MongoOperations 等相關類別與介面 Java-Based Query Interface Query 與 Criteria 等相關類別 Repository Programming Approach Repository 等相關介面
  • 23. Spring Data MongoDB 切入點 http://static.springsource.org/spring-data/data-mongodb/docs/current/. reference/html/#mongo.mongo-java-config MongoDB Java Driver: Mongo 類別 Spring Data MongoDB: MongoDbFactory 介面與 SimpleMongoDbFactory 類別 <mongo:mongo> 或 <mongo:db-factory> MongoTemplate 類別
  • 24. . MongoTemplate Spring Data MongoDB 的核心 實作 MongoOperations 介面,模擬 Collection 相關功能 預設透過 MongoMappingConverter 類別提供 Object-Document Mapping 功能 提供方便的 CRUD 相關操作 所㈲的 Exception 都轉換為 Spring 的 DataAccessException 提供 Callback 機制㈺叫 Java Driver 的 API Thread-Safe
  • 25. SpringSource Tool Suite 組態設定. http://www.springsource.org/sts
  • 26. . MongoTemplate 宣告方式 1 <?xml version="1.0" encoding="UTF-8"?> 2 <beans 3 xmlns="http://www.springframework.org/schema/beans" 4 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 5 xmlns:context="http://www.springframework.org/schema/context" 6 xmlns:mongo="http://www.springframework.org/schema/data/mongo" 7 xsi:schemaLocation= 8 "http://www.springframework.org/schema/beans 9 http://www.springframework.org/schema/beans/spring-beans.xsd10 http://www.springframework.org/schema/context11 http://www.springframework.org/schema/context/spring-context-3.1.xsd12 http://www.springframework.org/schema/data/mongo13 http://www.springframework.org/schema/data/mongo/spring-mongo-1.1.xsd>1415 <mongo:db-factory id="mongoDbFactory"16 host="localhost" port="27017" dbname="cities" />1718 <bean id="mongoTemplate"19 class="org.springframework.data.mongodb.core.MongoTemplate">20 <constructor-arg name="mongoDbFactory" ref="mongoDbFactory" />21 </bean>22 </beans>
  • 27. . MongoTemplate 取得方式 1 public class MongoDBUtils { 2 private static ApplicationContext factory = null; 3 private static MongoTemplate mongoTemplate = null; 4 5 static { 6 factory = 7 new ClassPathXmlApplicationContext("applicationContext.xml"); 8 mongoTemplate = (MongoTemplate) factory.getBean("mongoTemplate"); 9 }1011 public static MongoTemplate getMongoTemplate() {12 return mongoTemplate;13 }14 }
  • 28. . Spring Data MongoDB ㈾料存取方式 1 public class CityFinder { 2 public static void main(String[] args) { 3 MongoOperations mongoOps = MongoDBUtils.getMongoTemplate(); 4 5 Query query = new Query(Criteria.where("_id").is("90210")); 6 System.out.println("Found = " + mongoOps.count(query, "zips")); 7 8 City city = mongoOps.findOne(query, City.class, "zips"); 9 double[] loc = city.getLoc();10 System.out.println("City = " + city.getCity());11 System.out.println("Location = [" + loc[0] + ", " + loc[1] + "]");12 }13 }
  • 29. MongoConverter http://static.springsource.org/spring-data/data-mongodb/docs/current/. reference/html/#mapping-chapter 負責 Object-Document Mapping 功能 提供 SimpleMappingConverter 與 MongoMappingConverter 等實作 類別,預設使用 MongoMappingConverter 類別 可以直接對 Domain Object 進行轉換,也可 以提供 Metadata 輔助轉換 _id 預設會對應到 id 或㈲ @Id 註記的欄位,型 別支援 String、ObjectId 與 BigInteger 各種型別的對應會透過 MongoTypeMapper 介面的實 作類別來進行,預設是 DefaultMongoTypeMapper 類別
  • 30. Metadata Mapping http://static.springsource.org/spring-data/data-mongodb/docs/current/. reference/html/#mapping-chapter @Document(collection="collectionName") @Field(value="fieldName") @Id @Indexed @CompoundIndex @GeoSpatialIndexed @DBRef …
  • 31. . Embedding Document 表示方式 1 @Document(collection="publishers") 2 public class Publisher implements Serializable { 3 @Id 4 private String publisherId; 5 private String publisherName; 6 } 1 @Document(collection="books") 2 public class Book implements Serializable { 3 @Id 4 private BigInteger bookId; 5 @Field(value="title") 6 private String title; 7 private Publisher publisher; 8 }
  • 32. . Embedding Document Client 端 1 public class BookManager { 2 public static void main(String[] args) { 3 MongoOperations mongoOps = MongoDBUtils.getMongoTemplate(); 4 mongoOps.dropCollection("booklistings"); 5 6 Publisher publisher = new Publisher("OA", "OReilly & Associates"); 7 Book book1 = new Book("MongoDB: The Definitive Guide", publisher); 8 Book book2 = new Book("MongoDB技術手冊", publisher); 9 mongoOps.insert(book1);10 mongoOps.insert(book2);1112 Query query = new Query(Criteria.where("title").regex(".*Mongo.*"));13 Book book = mongoOps.findOne(query, Book.class, "booklistings");14 System.out.print("Publisher = ");15 System.out.println(book.getPublisher().getPublisherName());16 }17 }
  • 33. . Embedding Document 輸出結果
  • 34. . DBRef Document 表示方式(雙向) 1 @Document(collection="books") 2 public class Book implements Serializable { 3 @Id 4 private BigInteger bookId; 5 private String title; 6 @DBRef 7 private Publisher publisher; 8 } 1 @Document(collection="publishers") 2 public class Publisher implements Serializable { 3 @Id 4 private String publisherId; 5 private String publisherName; 6 @DBRef 7 private List<Book> books = new ArrayList<Book>(0); 8 }
  • 35. . DBRef Document Client 端(雙向) 1 public class TwoWayBookManager { 2 public static void main(String[] args) { 3 MongoOperations mongoOps = MongoDBUtils.getMongoTemplate(); 4 mongoOps.dropCollection("publishers"); 5 mongoOps.dropCollection("books"); 6 7 Publisher publisher = new Publisher("OA", "OReilly & Associates"); 8 mongoOps.insert(publisher); 910 Book book1 = new Book("MongoDB: The Definitive Guide", publisher);11 Book book2 = new Book("MongoDB技術手冊", publisher);12 mongoOps.insert(book1); mongoOps.insert(book2);1314 List<Book> bookList = mongoOps.find(new Query(), Book.class);15 publisher.setBooks(bookList);16 mongoOps.save(publisher);1718 // 以㆖為止OK,底㆘會產生例外19 Query query = new Query(Criteria.where("title").regex(".*Mongo.*"));20 Book book = mongoOps.findOne(query, Book.class);21 }22 }
  • 36. . DBRef Document 輸出結果(雙向)
  • 37. . DBRef Document 表示方式(單向) 1 @Document(collection="books") 2 public class Book implements Serializable { 3 @Id 4 private BigInteger bookId; 5 private String title; 6 @DBRef 7 private Publisher publisher; 8 } 1 @Document(collection="publishers") 2 public class Publisher implements Serializable { 3 @Id 4 private String publisherId; 5 private String publisherName; 6 }
  • 38. . DBRef Document Client 端(單向) 1 public class OneWayBookManager { 2 public static void main(String[] args) { 3 MongoOperations mongoOps = MongoDBUtils.getMongoTemplate(); 4 mongoOps.dropCollection("publishers"); 5 mongoOps.dropCollection("books"); 6 7 Publisher publisher = new Publisher("OA", "OReilly & Associates"); 8 mongoOps.insert(publisher); 910 Book book1 = new Book("MongoDB: The Definitive Guide", publisher);11 Book book2 = new Book("MongoDB技術手冊", publisher);12 mongoOps.insert(book1);13 mongoOps.insert(book2);1415 Query query = new Query(Criteria.where("title").regex(".*Mongo.*"));16 Book book = mongoOps.findOne(query, Book.class);17 System.out.print("Publisher = ");18 System.out.println(book.getPublisher().getPublisherName());19 }20 }
  • 39. . DBRef Document 輸出結果(單向)
  • 40. ㈾策會教研所 ㈾訊技術訓練㆗心. http://www.iiiedu.org.tw/taipei