SlideShare uma empresa Scribd logo
1 de 40
Baixar para ler offline
.

.
       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

Mais conteúdo relacionado

Mais procurados

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
Tobias Trelle
 
DB エンジニアのマイクロサービス入門〜Oracle Database と Docker ではじめる API サービス〜
DB エンジニアのマイクロサービス入門〜Oracle Database と  Docker ではじめる API サービス〜DB エンジニアのマイクロサービス入門〜Oracle Database と  Docker ではじめる API サービス〜
DB エンジニアのマイクロサービス入門〜Oracle Database と Docker ではじめる API サービス〜
Michitoshi Yoshida
 
MongoDB全機能解説1
MongoDB全機能解説1MongoDB全機能解説1
MongoDB全機能解説1
Takahiro Inoue
 

Mais procurados (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] 아파치 피그를 위한 테즈 연산 엔진 개발하기 최종
 

Destaque

Java Persistence Frameworks for MongoDB
Java Persistence Frameworks for MongoDBJava Persistence Frameworks for MongoDB
Java Persistence Frameworks for MongoDB
MongoDB
 

Destaque (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
 

Semelhante a Spring Data 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
 
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
Minsk MongoDB User Group
 
Smoothing Your Java with DSLs
Smoothing Your Java with DSLsSmoothing Your Java with DSLs
Smoothing Your Java with DSLs
intelliyole
 

Semelhante a 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
 

Último

CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Service
giselly40
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and Myths
Joaquim Jorge
 

Último (20)

Factors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxFactors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
 
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUnderstanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
 
A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024
 
CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Service
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonets
 
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
 
Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and Myths
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024
 
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
 
The Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxThe Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptx
 
Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processors
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
 

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