SlideShare ist ein Scribd-Unternehmen logo
1 von 40
Downloaden Sie, um offline zu lesen
.

.
       Spring Data MongoDB

                    蘇國鈞
            monster.kcsu@gmail.com
    http://www.facebook.com/monster.kcsu


           November 17, 2012
. 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 端的整合運用
. Outline

   .
   1   MongoDB


   .
   2   MongoDB Java Driver


   .
   3   Spring Data MongoDB
.
1   MongoDB


.
2   MongoDB Java Driver


.
3   Spring Data MongoDB
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 版
. RDBMS vs. MongoDB
   RDBMS         MongoDB
   Database      Database
   Table         Collection
   Record/Row    Document
   Column        Field
   Primary Key   _id
. 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'],
10
11       image:
12       {
13           url: 'http://example.com/db.jpg',
14           caption: '',
15           type: 'jpg',
16           size: 75381,
17           data: "Binary"
18       }
19   }
. 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(...)
. 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   }
. JavaScript Shell Output
.
1   MongoDB


.
2   MongoDB Java Driver


.
3   Spring Data MongoDB
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
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   }
. 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       }
12
13       public static DB getDB(String dbName) {
14           return mongo.getDB(dbName);
15       }
16
17       public static DBCollection getCollection(String dbName, String colName) {
18           return mongo.getDB(dbName).getCollection(colName);
19       }
20   }
. 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);
 9
10           System.out.println(doc);
11
12           Gson gson = new Gson();
13           City city = gson.fromJson(doc.toString(), City.class);
14
15           System.out.println("City = " + city.getCity());
16           System.out.println("Longitude = " + city.getLoc()[0]);
17           System.out.println("Latitude = " + city.getLoc()[1]);
18       }
19   }
.
1   MongoDB


.
2   MongoDB Java Driver


.
3   Spring Data MongoDB
Spring Data
.   http://www.springsource.org/spring-data
. Spring Data
  希望能夠透過 Spring 整合重要的㈾料存取技術:
     透過 Spring 存取 RDBMS、NoSQL、與
     MapReduce Framework
     基本㆖只是個技術統稱,每個 RDBMS/
     NoSQL 的存取方式都不盡相同
  目前 Spring Data 家族包括:
     Spring   Data   Hadoop
     Spring   Data   JPA
     Spring   Data   MongoDB
     Spring   Data   Neo4j
     …
Spring Data MongoDB
.   http://www.springsource.org/spring-data/mongodb
. Spring Data MongoDB
     希望能夠透過 Spring 整合 MongoDB 這種
     Document 型態的㈾料存取技術
     提供高階的 Template 封裝對 Document 的
     相關操作,跟 Spring 整合 JDBC 與
     Hibernate 的方式很類似
     可以整合 Spring 的 IoC 與 Data Access
     Exception Hierarchy 等功能,也可以直接使
     用高階的 Template 支援
     官方文件裡面也稱為 Spring Data Document
     或 DATADOC
. 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
. Spring Data MongoDB 主要功能
    High-Level Template-Style Support
    MongoTemplate 與 MongoOperations 等相關類別與介面

    Java-Based Query Interface
    Query 與 Criteria 等相關類別

    Repository Programming Approach
    Repository 等相關介面
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    類別
. MongoTemplate
     Spring Data MongoDB 的核心
     實作 MongoOperations 介面,模擬 Collection 相關功能
     預設透過 MongoMappingConverter 類別提供
     Object-Document Mapping 功能
     提供方便的 CRUD 相關操作
     所㈲的 Exception 都轉換為 Spring 的
     DataAccessException

     提供 Callback 機制㈺叫 Java Driver 的 API
     Thread-Safe
SpringSource Tool Suite 組態設定
.   http://www.springsource.org/sts
. 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.xsd
10           http://www.springframework.org/schema/context
11           http://www.springframework.org/schema/context/spring-context-3.1.xsd
12           http://www.springframework.org/schema/data/mongo
13           http://www.springframework.org/schema/data/mongo/spring-mongo-1.1.xsd>
14
15       <mongo:db-factory id="mongoDbFactory"
16           host="localhost" port="27017" dbname="cities" />
17
18       <bean id="mongoTemplate"
19            class="org.springframework.data.mongodb.core.MongoTemplate">
20            <constructor-arg name="mongoDbFactory" ref="mongoDbFactory" />
21       </bean>
22   </beans>
. 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       }
10
11       public static MongoTemplate getMongoTemplate() {
12           return mongoTemplate;
13       }
14   }
. 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   }
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 類別
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

            …
. 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   }
. 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", "O'Reilly & 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);
11
12           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   }
. Embedding Document 輸出結果
. 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   }
. 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", "O'Reilly & Associates");
 8           mongoOps.insert(publisher);
 9
10           Book book1 = new Book("MongoDB: The Definitive Guide", publisher);
11           Book book2 = new Book("MongoDB技術手冊", publisher);
12           mongoOps.insert(book1);    mongoOps.insert(book2);
13
14           List<Book> bookList = mongoOps.find(new Query(), Book.class);
15           publisher.setBooks(bookList);
16           mongoOps.save(publisher);
17
18           // 以㆖為止OK,底㆘會產生例外
19           Query query = new Query(Criteria.where("title").regex(".*Mongo.*"));
20           Book book = mongoOps.findOne(query, Book.class);
21       }
22   }
. DBRef Document 輸出結果(雙向)
. 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 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", "O'Reilly & Associates");
 8           mongoOps.insert(publisher);
 9
10           Book book1 = new Book("MongoDB: The Definitive Guide", publisher);
11           Book book2 = new Book("MongoDB技術手冊", publisher);
12           mongoOps.insert(book1);
13           mongoOps.insert(book2);
14
15           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   }
. DBRef Document 輸出結果(單向)
㈾策會教研所 ㈾訊技術訓練㆗心
.   http://www.iiiedu.org.tw/taipei

Weitere ähnliche Inhalte

Was ist angesagt?

Fluentd and Embulk Game Server 4
Fluentd and Embulk Game Server 4Fluentd and Embulk Game Server 4
Fluentd and Embulk Game Server 4N Masahiro
 
BedCon 2013 - Java Persistenz-Frameworks für MongoDB
BedCon 2013 - Java Persistenz-Frameworks für MongoDBBedCon 2013 - Java Persistenz-Frameworks für MongoDB
BedCon 2013 - Java Persistenz-Frameworks für MongoDBTobias Trelle
 
OSCON 2011 Learning CouchDB
OSCON 2011 Learning CouchDBOSCON 2011 Learning CouchDB
OSCON 2011 Learning CouchDBBradley Holt
 
OSCON 2011 CouchApps
OSCON 2011 CouchAppsOSCON 2011 CouchApps
OSCON 2011 CouchAppsBradley Holt
 
Optimize drupal using mongo db
Optimize drupal using mongo dbOptimize drupal using mongo db
Optimize drupal using mongo dbVladimir Ilic
 
SpringBoot with MyBatis, Flyway, QueryDSL
SpringBoot with MyBatis, Flyway, QueryDSLSpringBoot with MyBatis, Flyway, QueryDSL
SpringBoot with MyBatis, Flyway, QueryDSLSunghyouk Bae
 
Sbt職人のススメ
Sbt職人のススメSbt職人のススメ
Sbt職人のススメ潤一 加藤
 
An introduction to CouchDB
An introduction to CouchDBAn introduction to CouchDB
An introduction to CouchDBDavid Coallier
 
Big Data Step-by-Step: Infrastructure 3/3: Taking it to the cloud... easily.....
Big Data Step-by-Step: Infrastructure 3/3: Taking it to the cloud... easily.....Big Data Step-by-Step: Infrastructure 3/3: Taking it to the cloud... easily.....
Big Data Step-by-Step: Infrastructure 3/3: Taking it to the cloud... easily.....Jeffrey Breen
 
Mongo db pefrormance optimization strategies
Mongo db pefrormance optimization strategiesMongo db pefrormance optimization strategies
Mongo db pefrormance optimization strategiesronwarshawsky
 
Hops - Distributed metadata for Hadoop
Hops - Distributed metadata for HadoopHops - Distributed metadata for Hadoop
Hops - Distributed metadata for HadoopJim Dowling
 
Automating Workflows for Analytics Pipelines
Automating Workflows for Analytics PipelinesAutomating Workflows for Analytics Pipelines
Automating Workflows for Analytics PipelinesSadayuki Furuhashi
 
DB エンジニアのマイクロサービス入門〜Oracle Database と Docker ではじめる API サービス〜
DB エンジニアのマイクロサービス入門〜Oracle Database と  Docker ではじめる API サービス〜DB エンジニアのマイクロサービス入門〜Oracle Database と  Docker ではじめる API サービス〜
DB エンジニアのマイクロサービス入門〜Oracle Database と Docker ではじめる API サービス〜Michitoshi Yoshida
 
Hazelcast
HazelcastHazelcast
Hazelcastoztalip
 
[2A5]하둡 보안 어떻게 해야 할까
[2A5]하둡 보안 어떻게 해야 할까[2A5]하둡 보안 어떻게 해야 할까
[2A5]하둡 보안 어떻게 해야 할까NAVER D2
 
MongoDB全機能解説1
MongoDB全機能解説1MongoDB全機能解説1
MongoDB全機能解説1Takahiro Inoue
 
Logging for Production Systems in The Container Era
Logging for Production Systems in The Container EraLogging for Production Systems in The Container Era
Logging for Production Systems in The Container EraSadayuki Furuhashi
 
[2C1] 아파치 피그를 위한 테즈 연산 엔진 개발하기 최종
[2C1] 아파치 피그를 위한 테즈 연산 엔진 개발하기 최종[2C1] 아파치 피그를 위한 테즈 연산 엔진 개발하기 최종
[2C1] 아파치 피그를 위한 테즈 연산 엔진 개발하기 최종NAVER D2
 

Was ist angesagt? (20)

Fluentd and Embulk Game Server 4
Fluentd and Embulk Game Server 4Fluentd and Embulk Game Server 4
Fluentd and Embulk Game Server 4
 
BedCon 2013 - Java Persistenz-Frameworks für MongoDB
BedCon 2013 - Java Persistenz-Frameworks für MongoDBBedCon 2013 - Java Persistenz-Frameworks für MongoDB
BedCon 2013 - Java Persistenz-Frameworks für MongoDB
 
OSCON 2011 Learning CouchDB
OSCON 2011 Learning CouchDBOSCON 2011 Learning CouchDB
OSCON 2011 Learning CouchDB
 
OSCON 2011 CouchApps
OSCON 2011 CouchAppsOSCON 2011 CouchApps
OSCON 2011 CouchApps
 
CouchDB
CouchDBCouchDB
CouchDB
 
re:dash is awesome
re:dash is awesomere:dash is awesome
re:dash is awesome
 
Optimize drupal using mongo db
Optimize drupal using mongo dbOptimize drupal using mongo db
Optimize drupal using mongo db
 
SpringBoot with MyBatis, Flyway, QueryDSL
SpringBoot with MyBatis, Flyway, QueryDSLSpringBoot with MyBatis, Flyway, QueryDSL
SpringBoot with MyBatis, Flyway, QueryDSL
 
Sbt職人のススメ
Sbt職人のススメSbt職人のススメ
Sbt職人のススメ
 
An introduction to CouchDB
An introduction to CouchDBAn introduction to CouchDB
An introduction to CouchDB
 
Big Data Step-by-Step: Infrastructure 3/3: Taking it to the cloud... easily.....
Big Data Step-by-Step: Infrastructure 3/3: Taking it to the cloud... easily.....Big Data Step-by-Step: Infrastructure 3/3: Taking it to the cloud... easily.....
Big Data Step-by-Step: Infrastructure 3/3: Taking it to the cloud... easily.....
 
Mongo db pefrormance optimization strategies
Mongo db pefrormance optimization strategiesMongo db pefrormance optimization strategies
Mongo db pefrormance optimization strategies
 
Hops - Distributed metadata for Hadoop
Hops - Distributed metadata for HadoopHops - Distributed metadata for Hadoop
Hops - Distributed metadata for Hadoop
 
Automating Workflows for Analytics Pipelines
Automating Workflows for Analytics PipelinesAutomating Workflows for Analytics Pipelines
Automating Workflows for Analytics Pipelines
 
DB エンジニアのマイクロサービス入門〜Oracle Database と Docker ではじめる API サービス〜
DB エンジニアのマイクロサービス入門〜Oracle Database と  Docker ではじめる API サービス〜DB エンジニアのマイクロサービス入門〜Oracle Database と  Docker ではじめる API サービス〜
DB エンジニアのマイクロサービス入門〜Oracle Database と Docker ではじめる API サービス〜
 
Hazelcast
HazelcastHazelcast
Hazelcast
 
[2A5]하둡 보안 어떻게 해야 할까
[2A5]하둡 보안 어떻게 해야 할까[2A5]하둡 보안 어떻게 해야 할까
[2A5]하둡 보안 어떻게 해야 할까
 
MongoDB全機能解説1
MongoDB全機能解説1MongoDB全機能解説1
MongoDB全機能解説1
 
Logging for Production Systems in The Container Era
Logging for Production Systems in The Container EraLogging for Production Systems in The Container Era
Logging for Production Systems in The Container Era
 
[2C1] 아파치 피그를 위한 테즈 연산 엔진 개발하기 최종
[2C1] 아파치 피그를 위한 테즈 연산 엔진 개발하기 최종[2C1] 아파치 피그를 위한 테즈 연산 엔진 개발하기 최종
[2C1] 아파치 피그를 위한 테즈 연산 엔진 개발하기 최종
 

Andere mochten auch

HDInsight for Microsoft Users
HDInsight for Microsoft UsersHDInsight for Microsoft Users
HDInsight for Microsoft UsersKuo-Chun Su
 
打開窗,讓大象跨進來 - Microsoft HDInsight
打開窗,讓大象跨進來 - Microsoft HDInsight打開窗,讓大象跨進來 - Microsoft HDInsight
打開窗,讓大象跨進來 - Microsoft HDInsightKuo-Chun Su
 
Hadoop 設定與配置
Hadoop 設定與配置Hadoop 設定與配置
Hadoop 設定與配置鳥 藍
 
HDInsight for Hadoopers
HDInsight for HadoopersHDInsight for Hadoopers
HDInsight for HadoopersKuo-Chun Su
 
從 Web Site 到 Web Application,從 Web Services 到 Mobile Services
從 Web Site 到 Web Application,從 Web Services 到 Mobile Services從 Web Site 到 Web Application,從 Web Services 到 Mobile Services
從 Web Site 到 Web Application,從 Web Services 到 Mobile ServicesKuo-Chun Su
 
MongoDB + Java - Everything you need to know
MongoDB + Java - Everything you need to know MongoDB + Java - Everything you need to know
MongoDB + Java - Everything you need to know Norberto Leite
 
Big Java, Big Data
Big Java, Big DataBig Java, Big Data
Big Java, Big DataKuo-Chun Su
 
Hadoop, the Apple of Our Eyes (這些年,我們一起追的 Hadoop)
Hadoop, the Apple of Our Eyes (這些年,我們一起追的 Hadoop)Hadoop, the Apple of Our Eyes (這些年,我們一起追的 Hadoop)
Hadoop, the Apple of Our Eyes (這些年,我們一起追的 Hadoop)Kuo-Chun Su
 
Java Persistence Frameworks for MongoDB
Java Persistence Frameworks for MongoDBJava Persistence Frameworks for MongoDB
Java Persistence Frameworks for MongoDBMongoDB
 

Andere mochten auch (9)

HDInsight for Microsoft Users
HDInsight for Microsoft UsersHDInsight for Microsoft Users
HDInsight for Microsoft Users
 
打開窗,讓大象跨進來 - Microsoft HDInsight
打開窗,讓大象跨進來 - Microsoft HDInsight打開窗,讓大象跨進來 - Microsoft HDInsight
打開窗,讓大象跨進來 - Microsoft HDInsight
 
Hadoop 設定與配置
Hadoop 設定與配置Hadoop 設定與配置
Hadoop 設定與配置
 
HDInsight for Hadoopers
HDInsight for HadoopersHDInsight for Hadoopers
HDInsight for Hadoopers
 
從 Web Site 到 Web Application,從 Web Services 到 Mobile Services
從 Web Site 到 Web Application,從 Web Services 到 Mobile Services從 Web Site 到 Web Application,從 Web Services 到 Mobile Services
從 Web Site 到 Web Application,從 Web Services 到 Mobile Services
 
MongoDB + Java - Everything you need to know
MongoDB + Java - Everything you need to know MongoDB + Java - Everything you need to know
MongoDB + Java - Everything you need to know
 
Big Java, Big Data
Big Java, Big DataBig Java, Big Data
Big Java, Big Data
 
Hadoop, the Apple of Our Eyes (這些年,我們一起追的 Hadoop)
Hadoop, the Apple of Our Eyes (這些年,我們一起追的 Hadoop)Hadoop, the Apple of Our Eyes (這些年,我們一起追的 Hadoop)
Hadoop, the Apple of Our Eyes (這些年,我們一起追的 Hadoop)
 
Java Persistence Frameworks for MongoDB
Java Persistence Frameworks for MongoDBJava Persistence Frameworks for MongoDB
Java Persistence Frameworks for MongoDB
 

Ähnlich wie Spring Data MongoDB 介紹

Webinar: Building Your First App with MongoDB and Java
Webinar: Building Your First App with MongoDB and JavaWebinar: Building Your First App with MongoDB and Java
Webinar: Building Your First App with MongoDB and JavaMongoDB
 
Java Persistence Frameworks for MongoDB
Java Persistence Frameworks for MongoDBJava Persistence Frameworks for MongoDB
Java Persistence Frameworks for MongoDBTobias Trelle
 
Getting started with MongoDB and Scala - Open Source Bridge 2012
Getting started with MongoDB and Scala - Open Source Bridge 2012Getting started with MongoDB and Scala - Open Source Bridge 2012
Getting started with MongoDB and Scala - Open Source Bridge 2012sullis
 
Meteoro de pegasuus! Desenvolvendo aplicações realtime com MeteorJS
Meteoro de pegasuus! Desenvolvendo aplicações realtime com MeteorJSMeteoro de pegasuus! Desenvolvendo aplicações realtime com MeteorJS
Meteoro de pegasuus! Desenvolvendo aplicações realtime com MeteorJSJulio Antonio Mendonça de Marins
 
MongoDB World 2016: From the Polls to the Trolls: Seeing What the World Think...
MongoDB World 2016: From the Polls to the Trolls: Seeing What the World Think...MongoDB World 2016: From the Polls to the Trolls: Seeing What the World Think...
MongoDB World 2016: From the Polls to the Trolls: Seeing What the World Think...MongoDB
 
Java Development with MongoDB (James Williams)
Java Development with MongoDB (James Williams)Java Development with MongoDB (James Williams)
Java Development with MongoDB (James Williams)MongoSF
 
mongodb-introduction
mongodb-introductionmongodb-introduction
mongodb-introductionTse-Ching Ho
 
Spring Data, Jongo & Co.
Spring Data, Jongo & Co.Spring Data, Jongo & Co.
Spring Data, Jongo & Co.Tobias Trelle
 
Morphia, Spring Data & Co.
Morphia, Spring Data & Co.Morphia, Spring Data & Co.
Morphia, Spring Data & Co.Tobias Trelle
 
This upload requires better support for ODP format
This upload requires better support for ODP formatThis upload requires better support for ODP format
This upload requires better support for ODP formatForest Mars
 
Back to Basics Webinar 2 - Your First MongoDB Application
Back to  Basics Webinar 2 - Your First MongoDB ApplicationBack to  Basics Webinar 2 - Your First MongoDB Application
Back to Basics Webinar 2 - Your First MongoDB ApplicationJoe Drumgoole
 
Back to Basics Webinar 2: Your First MongoDB Application
Back to Basics Webinar 2: Your First MongoDB ApplicationBack to Basics Webinar 2: Your First MongoDB Application
Back to Basics Webinar 2: Your First MongoDB ApplicationMongoDB
 
Meetup#1: 10 reasons to fall in love with MongoDB
Meetup#1: 10 reasons to fall in love with MongoDBMeetup#1: 10 reasons to fall in love with MongoDB
Meetup#1: 10 reasons to fall in love with MongoDBMinsk MongoDB User Group
 
Introduction to MongoDB
Introduction to MongoDBIntroduction to MongoDB
Introduction to MongoDBChun-Kai Wang
 
Smoothing Your Java with DSLs
Smoothing Your Java with DSLsSmoothing Your Java with DSLs
Smoothing Your Java with DSLsintelliyole
 
Back to Basics 2017: Mí primera aplicación MongoDB
Back to Basics 2017: Mí primera aplicación MongoDBBack to Basics 2017: Mí primera aplicación MongoDB
Back to Basics 2017: Mí primera aplicación MongoDBMongoDB
 

Ähnlich wie Spring Data MongoDB 介紹 (20)

Webinar: Building Your First App with MongoDB and Java
Webinar: Building Your First App with MongoDB and JavaWebinar: Building Your First App with MongoDB and Java
Webinar: Building Your First App with MongoDB and Java
 
Java Persistence Frameworks for MongoDB
Java Persistence Frameworks for MongoDBJava Persistence Frameworks for MongoDB
Java Persistence Frameworks for MongoDB
 
Getting started with MongoDB and Scala - Open Source Bridge 2012
Getting started with MongoDB and Scala - Open Source Bridge 2012Getting started with MongoDB and Scala - Open Source Bridge 2012
Getting started with MongoDB and Scala - Open Source Bridge 2012
 
Meteoro de pegasuus! Desenvolvendo aplicações realtime com MeteorJS
Meteoro de pegasuus! Desenvolvendo aplicações realtime com MeteorJSMeteoro de pegasuus! Desenvolvendo aplicações realtime com MeteorJS
Meteoro de pegasuus! Desenvolvendo aplicações realtime com MeteorJS
 
MongoDB World 2016: From the Polls to the Trolls: Seeing What the World Think...
MongoDB World 2016: From the Polls to the Trolls: Seeing What the World Think...MongoDB World 2016: From the Polls to the Trolls: Seeing What the World Think...
MongoDB World 2016: From the Polls to the Trolls: Seeing What the World Think...
 
Java Development with MongoDB (James Williams)
Java Development with MongoDB (James Williams)Java Development with MongoDB (James Williams)
Java Development with MongoDB (James Williams)
 
mongodb-introduction
mongodb-introductionmongodb-introduction
mongodb-introduction
 
Spring Data, Jongo & Co.
Spring Data, Jongo & Co.Spring Data, Jongo & Co.
Spring Data, Jongo & Co.
 
Mongo-Drupal
Mongo-DrupalMongo-Drupal
Mongo-Drupal
 
A Brief MongoDB Intro
A Brief MongoDB IntroA Brief MongoDB Intro
A Brief MongoDB Intro
 
Morphia, Spring Data & Co.
Morphia, Spring Data & Co.Morphia, Spring Data & Co.
Morphia, Spring Data & Co.
 
Scripting GeoServer
Scripting GeoServerScripting GeoServer
Scripting GeoServer
 
This upload requires better support for ODP format
This upload requires better support for ODP formatThis upload requires better support for ODP format
This upload requires better support for ODP format
 
Back to Basics Webinar 2 - Your First MongoDB Application
Back to  Basics Webinar 2 - Your First MongoDB ApplicationBack to  Basics Webinar 2 - Your First MongoDB Application
Back to Basics Webinar 2 - Your First MongoDB Application
 
Back to Basics Webinar 2: Your First MongoDB Application
Back to Basics Webinar 2: Your First MongoDB ApplicationBack to Basics Webinar 2: Your First MongoDB Application
Back to Basics Webinar 2: Your First MongoDB Application
 
Meetup#1: 10 reasons to fall in love with MongoDB
Meetup#1: 10 reasons to fall in love with MongoDBMeetup#1: 10 reasons to fall in love with MongoDB
Meetup#1: 10 reasons to fall in love with MongoDB
 
Introduction to MongoDB
Introduction to MongoDBIntroduction to MongoDB
Introduction to MongoDB
 
Smoothing Your Java with DSLs
Smoothing Your Java with DSLsSmoothing Your Java with DSLs
Smoothing Your Java with DSLs
 
MongoDB
MongoDBMongoDB
MongoDB
 
Back to Basics 2017: Mí primera aplicación MongoDB
Back to Basics 2017: Mí primera aplicación MongoDBBack to Basics 2017: Mí primera aplicación MongoDB
Back to Basics 2017: Mí primera aplicación MongoDB
 

Kürzlich hochgeladen

TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024Lonnie McRorey
 
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptx
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptxPasskey Providers and Enabling Portability: FIDO Paris Seminar.pptx
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptxLoriGlavin3
 
How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.Curtis Poe
 
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek SchlawackFwdays
 
"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr BaganFwdays
 
The Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsThe Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsPixlogix Infotech
 
DSPy a system for AI to Write Prompts and Do Fine Tuning
DSPy a system for AI to Write Prompts and Do Fine TuningDSPy a system for AI to Write Prompts and Do Fine Tuning
DSPy a system for AI to Write Prompts and Do Fine TuningLars Bell
 
The State of Passkeys with FIDO Alliance.pptx
The State of Passkeys with FIDO Alliance.pptxThe State of Passkeys with FIDO Alliance.pptx
The State of Passkeys with FIDO Alliance.pptxLoriGlavin3
 
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptxThe Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptxLoriGlavin3
 
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdf
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdfHyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdf
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdfPrecisely
 
From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .Alan Dix
 
Unleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubUnleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubKalema Edgar
 
SAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptxSAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptxNavinnSomaal
 
Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Mattias Andersson
 
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Mark Simos
 
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024BookNet Canada
 
What is DBT - The Ultimate Data Build Tool.pdf
What is DBT - The Ultimate Data Build Tool.pdfWhat is DBT - The Ultimate Data Build Tool.pdf
What is DBT - The Ultimate Data Build Tool.pdfMounikaPolabathina
 
Take control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test SuiteTake control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test SuiteDianaGray10
 
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024BookNet Canada
 
DevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenDevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenHervé Boutemy
 

Kürzlich hochgeladen (20)

TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024
 
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptx
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptxPasskey Providers and Enabling Portability: FIDO Paris Seminar.pptx
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptx
 
How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.
 
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
 
"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan
 
The Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsThe Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and Cons
 
DSPy a system for AI to Write Prompts and Do Fine Tuning
DSPy a system for AI to Write Prompts and Do Fine TuningDSPy a system for AI to Write Prompts and Do Fine Tuning
DSPy a system for AI to Write Prompts and Do Fine Tuning
 
The State of Passkeys with FIDO Alliance.pptx
The State of Passkeys with FIDO Alliance.pptxThe State of Passkeys with FIDO Alliance.pptx
The State of Passkeys with FIDO Alliance.pptx
 
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptxThe Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
 
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdf
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdfHyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdf
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdf
 
From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .
 
Unleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubUnleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding Club
 
SAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptxSAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptx
 
Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?
 
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
 
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
 
What is DBT - The Ultimate Data Build Tool.pdf
What is DBT - The Ultimate Data Build Tool.pdfWhat is DBT - The Ultimate Data Build Tool.pdf
What is DBT - The Ultimate Data Build Tool.pdf
 
Take control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test SuiteTake control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test Suite
 
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
 
DevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenDevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache Maven
 

Spring Data MongoDB 介紹

  • 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'], 10 11 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 }
  • 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 } 12 13 public static DB getDB(String dbName) { 14 return mongo.getDB(dbName); 15 } 16 17 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); 9 10 System.out.println(doc); 11 12 Gson gson = new Gson(); 13 City city = gson.fromJson(doc.toString(), City.class); 14 15 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.xsd 10 http://www.springframework.org/schema/context 11 http://www.springframework.org/schema/context/spring-context-3.1.xsd 12 http://www.springframework.org/schema/data/mongo 13 http://www.springframework.org/schema/data/mongo/spring-mongo-1.1.xsd> 14 15 <mongo:db-factory id="mongoDbFactory" 16 host="localhost" port="27017" dbname="cities" /> 17 18 <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 } 10 11 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", "O'Reilly & 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); 11 12 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", "O'Reilly & Associates"); 8 mongoOps.insert(publisher); 9 10 Book book1 = new Book("MongoDB: The Definitive Guide", publisher); 11 Book book2 = new Book("MongoDB技術手冊", publisher); 12 mongoOps.insert(book1); mongoOps.insert(book2); 13 14 List<Book> bookList = mongoOps.find(new Query(), Book.class); 15 publisher.setBooks(bookList); 16 mongoOps.save(publisher); 17 18 // 以㆖為止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", "O'Reilly & Associates"); 8 mongoOps.insert(publisher); 9 10 Book book1 = new Book("MongoDB: The Definitive Guide", publisher); 11 Book book2 = new Book("MongoDB技術手冊", publisher); 12 mongoOps.insert(book1); 13 mongoOps.insert(book2); 14 15 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