SlideShare ist ein Scribd-Unternehmen logo
1 von 44
Downloaden Sie, um offline zu lesen
Simplify your
                 MongoDB Java cloud apps
                    with Spring Data
                          Thomas Risberg, Cloud Foundry Team,VMware
                                    trisberg@vmware.com
                                           @trisberg




                             Spring Data
Tuesday, December 4, 12                                               1
About me
                     Currently working on the Cloud Foundry
                     team at VMware
                 • Member of Spring Data Team
                     ‣ Co-author of “Spring Data” from O’Reilly
                 • Joined Spring Framework project in 2003
                     ‣ Co-author of “Professional Java
                       Development with the Spring
                       Framework” from Wrox



Tuesday, December 4, 12                                           2
Introducing - Spring Data
              • Data access landscape has changed considerably
              • RDBMS are still important and predominant
                     ‣ but no longer considered a “one size fits all” solution

              • Spring has always provided excellent data access support
                     ‣ Transaction Management
                     ‣ Portable data access exception hierarchy
                     ‣ JDBC – JdbcTemplate
                     ‣ ORM - Hibernate, JPA, JDO, Ibatis support
                     ‣ Cache support (Spring 3.1)

              • Spring Data project goal is to “refresh” Spring’s data
                   support


Tuesday, December 4, 12                                                         3
Spring Data - Mission Statement

                      “   Provide a familiar and consistent
                          Spring-based programming model for
                          Big Data, NoSQL, and relational stores
                          while retaining store-specific features
                          and capabilities.




Tuesday, December 4, 12                                            4
Spring Data
               Supported Technologies:




Tuesday, December 4, 12                  5
Spring Data Repository
           Spring Data Repository basics:
           Generic repository implementation
           Basic CRUD (create, read, update and delete) methods
           Generating code for queries defined in repository
              interface
              findAll
              findByName ...
           Pagination and sorting support
           Currently has JPA and Mongo implementations


Tuesday, December 4, 12                                            6
Spring Data CrudRepository
               • Interface for for a specific type
                 a repository
                               generic CRUD operations on




Tuesday, December 4, 12                                     7
Paging and Sorting Repository

      Paging and Sorting Repository:       Extends “CrudRepository”




       Usage:




                                       8
Tuesday, December 4, 12                                               8
Repository Finders
     Repository Finder Methods:




       Keyword examples :
             Keyword                  Sample                             Logical result
            GreaterThan     findByAgeGreaterThan(int age)                {"age" : {"$gt" : age}}
               LessThan      findByAgeLessThan(int age)                  {"age" : {"$lt" : age}}
               Between    findByAgeBetween(int from, int to)       {"age" : {"$gt" : from, "$lt" : to}}
               NotNull        findByFirstnameNotNull()               {”firstname" : {"$ne" : null}}
                  Null          findByFirstnameNull()                     {”firstname" : null}
                   Like   findByFirstnameLike(String pattern)   { "firstname" : { "$regex" : "pattern"}}
                                                     9
Tuesday, December 4, 12                                                                                  9
MongoDB Repository


                          public interface DeveloperRepository
                          	   	  extends MongoRepository<Developer, String> {
                          }



                                 MongoRepository extends
                                PagingAndSortingRepository,
                                       it’s all free ...


                                                 10
Tuesday, December 4, 12                                                         10
MongoDB Repository
                    or more control ...
                     public interface BookRepository extends Repository<Book, String> {
                     	
                     	    Book save(Book book);
                     	
                     	    Book findOne(String isbn);
                     	
                     	    void delete(String isbn);
                     	
                     	    List<Book> findAll();

                     	    List<Book> findByAuthors(Author author);

                     	    List<Book> findByPublishedGreaterThan(Date date);
                     	
                     	    List<Book> findByCategoriesIn(String[] categories);

                     	    List<Book> findByPublishedGreaterThanAndCategoriesIn(Date date,
                                 String[] categories);
                     }

                                                       11
Tuesday, December 4, 12                                                                     11
Spring Data and MongoDB Repository
               App deployed to cloud in 10 steps ...




                          LIVE DEMO
         https://github.com/trisberg/mongosv-books/tree/master/demo
Tuesday, December 4, 12                                               12
MongoTemplate
      Spring Data support for MongoDB:
      • MongoTemplate
        ✓MongoConverter interface for mapping Mongo
         documents
                  • Built-in Advanced Mapping
                     – Annotation based (@Document, @Id, @DbRef)
                  • MappingMongoConverter for POJO mapping support
                  • Leverage Spring 3.0 TypeConverters and SpEL
            ✓Exception translation
            ✓Java based Query, Criteria, and Update DSLs


Tuesday, December 4, 12                                              13
Mapping POJOs
           Annotations for mapping POJOs to documents:
           • @Document
                ✓Identifies a domain object to be persisted to MongoDB
           • @Id
                ✓Identifies a field should be used as the _id of the document
           • @Field
                ✓define custom metadata for document fields
                      ‣ value defines key to be used to store the field in the document
                      ‣ order specifies in which order various fields shall be stored
           • @DbRef
                ✓indicates the annotated field is to be stored using a DBRef



Tuesday, December 4, 12                                                                   14
MongoTemplate CRUD
       Commonly used MongoTemplate methods:
       • insert(object)
              ✓Inserts a mapped POJO as a document
       • save(object)
              ✓Inserts or updates a mapped POJO as a document
       • updateFirst(query, update, entityClass)
       • updateMulti(query, update, entityClass)
              ✓Executes an update statement for the collection of the entityClass
               -- either the first or multiple documents matching the query
       • remove(object)
              ✓Remove the given object from the collection by id




Tuesday, December 4, 12                                                             15
MongoTemplate Finders
        Commonly used MongoTemplate finder methods:
        • findById(id, entityClass)
               ✓Returns a document with the given id mapped onto the given
                entityClass
        • findOne(query, entityClass)
               ✓Returns the first document from the results of an ad-hoc query
                mapped onto the given entityClass
        • find(query, entityClass)
               ✓Returns a List of documents from the results of an ad-hoc query
                mapped onto the given entityClass
        • findAll(entityClass)
               ✓Returns a List of documents from the collection used by the entity
                class mapped onto the given entity class

Tuesday, December 4, 12                                                              16
Working with queries
        Commonly used Query and Criteria methods:
       • searchCriteria = Criteria.where("published").gte(startDate)
             ✓Creates a Criteria where a field is greater or equal to specified date
       • searchCriteria.and("categories").in((Object[])categoriesToMatch)
             ✓adds to the criteria a clause where a fields value included in
              passed in array of values
       • Query query = new Query(searchCriteria)
             ✓Creates a Query based on the Criteria built above.
       • mongoTemplate.find(query, Book.class)
             ✓Uses the Query built above to find all book documents that match
              the Criteria.




Tuesday, December 4, 12                                                            17
MongoTemplate Example

         Direct Usage of the Mongo Template:



                            Insert into “Person”
                                Collection
                                                      findOne using query: { "name" : "Joe"}
                                                         in db.collection: database.Person




                          Drop collection [database.person]



Tuesday, December 4, 12                                                                        18
Configuration
          Namespace support for MongoDB


      <beans xmlns="http://www.springframework.org/schema/beans"
      	    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
      	    xmlns:mongo="http://www.springframework.org/schema/data/mongo"
      	    xsi:schemaLocation="http://www.springframework.org/schema/data/mongo
                  http://www.springframework.org/schema/data/mongo/spring-mongo-1.0.xsd
                  http://www.springframework.org/schema/beans
                  http://www.springframework.org/schema/beans/spring-beans-3.1.xsd">
      	
      	    <bean id="mongoTemplate"
                  class="org.springframework.data.mongodb.core.MongoTemplate">
      	    	    <constructor-arg name="mongoDbFactory" ref="mongoDbFactory"/>
      	    </bean>

      	    <mongo:db-factory host="localhost" port="27017" dbname="db"/>
      	    	
      </beans>




Tuesday, December 4, 12                                                                   19
Using a custom mapper
                                     Create a custom mapper:
                                     @Component
                                     public class UriWriteConverter
                                     	 	 implements Converter<URI, DBObject> {

                                     	   public DBObject convert(URI source) {
                                     	   	 DBObject dbo = new BasicDBObject();
                                     	   	 dbo.put("URI", source.toString());
                                     	   	 return dbo;
                                     	   }
    Register it in                   }

    your app context:
     <mongo:mapping-converter id="mongoConverter">
     	 <mongo:custom-converters
     	 	 base-package="org.springframework.data.demo.convert" />
     </mongo:mapping-converter>

     <bean id="mongoTemplate"
           class="org.springframework.data.mongodb.core.MongoTemplate">
         <constructor-arg name="mongoDbFactory" ref="mongoDbFactory" />
         <constructor-arg name="mongoConverter" ref="mongoConverter"/>
     </bean>


Tuesday, December 4, 12                                                          20
Cloud Foundry configuration
          Namespace support for MongoDB
         <dependency>
             <groupId>org.cloudfoundry</groupId>
             <artifactId>cloudfoundry-runtime</artifactId>
             <version>0.8.2</version>
         </dependency>

         <repository>
             <id>org.springsource.maven.milestone</id>
             <name>Spring Framework Maven Milestone Repository</name>
             <url>http://repo.springsource.org/libs-milestone</url>
         </repository>


      <cloud:mongo-db-factory id="dbFactory" write-concern="SAFE">
          <cloud:mongo-options
              connections-per-host="10"
              max-wait-time="2000" />
      </cloud:mongo-db-factory>



Tuesday, December 4, 12                                                 21
Tuesday, December 4, 12   22
What is Cloud Foundry?
      • Cloud Foundry is a PaaS
            – The application platform will be delivered as a service in the
              cloud era
            – The industry calls this platform as a service (PaaS)
      • PaaS makes it much easier to deploy, run and scale
        applications
      • Cloud Foundry - the application platform for the cloud era
            – Integrated software stack
            – Application execution engine
            – Self-service application deployment
            – Automated application infrastructure provisioning
            – Curated, updated and operated as a service



Tuesday, December 4, 12                                                        23
Lots of choices

                                          Ap
                                                                                              .js
                                           pli




                                                                                          ce
                                                                                                    Private
                                            ca




                                                                                         rfa
                          Data Services
                                                  tio




                                                                                        nte
                                                                                                    Clouds
                                                      n




                                                                                      rI
                                                     Se




                                                                                 ide
                                                          rvi




                                                                                              Public

                                                                                 ov
                                                           ce




                                   Msg Services


                                                                               Pr
                                                                                              Clouds           Partners
                                                              Int




                                                                             d
                                                                          ou
                                                                  er




                                                                                                              .COM
                                                                     fa


                                                                          Cl


                                                                                  Micro
                                                                    ce




                                                    Other
                                                   Services
                                                                                  Clouds



Tuesday, December 4, 12                                                                                                   24
Many cloud providers




Tuesday, December 4, 12               25
Cloud Foundry - login & info
                    $ gem install vmc
                    ...
                    $ gem install tunnel-vmc-plugin
                    ...
                    $ vmc target api.cloudfoundry.com
                    Setting target to https://api.cloudfoundry.com... OK

                    $ vmc login trisberg@springdeveloper.com
                    target: https://api.cloudfoundry.com

                    Password> *****

                    Authenticating... OK

                    $ vmc info
                    VMware's Cloud Application Platform

                    target: https://api.cloudfoundry.com
                      version: 0.999
                      support: http://support.cloudfoundry.com

                    user: trisberg@springdeveloper.com




Tuesday, December 4, 12                                                    26
Cloud Foundry - runtimes & frameworks
                    $ vmc info --runtimes --frameworks
                    Getting runtimes... OK
                    Getting frameworks... OK

                    runtime   description
                    java      1.6.0_24
                    java7     1.7.0_04
                    node      0.4.12
                    node06    0.6.8
                    node08    0.8.2
                    ruby18    1.8.7p357
                    ruby19    1.9.2p180

                    framework    description
                    grails
                    java_web
                    lift
                    node
                    play
                    rack
                    rails3
                    sinatra
                    spring
                    standalone




Tuesday, December 4, 12                                  27
Cloud Foundry - services
                 $ vmc info --services
                 Getting services... OK

                 service      version     provider   description
                 mongodb      2.0         core       MongoDB NoSQL store
                 mysql        5.1         core       MySQL database service
                 postgresql   9.0         core       PostgreSQL database service (vFabric)
                 rabbitmq     2.4         core       RabbitMQ message queue
                 redis        2.2         core       Redis key-value store service
                 redis        2.4         core       Redis key-value store service
                 redis        2.6         core       Redis key-value store service

                 $ vmc services
                 Getting services... OK

                 name                      service      version
                 mongodb-vtoons            mongodb      1.8
                 mysql-books               mysql        5.1
                 rabbit-test               rabbitmq     2.4
                 postgresql-eebf5          postgresql   9.0




Tuesday, December 4, 12                                                                      28
Cloud Foundry - provision a service

                    $ vmc create-service mongodb mongosv-books
                    Creating service mongosv-books... OK

                    $ vmc services
                    Getting services... OK

                    name                     service      version
                    mongosv-books            mongodb      2.0
                    mongodb-vtoons           mongodb      1.8
                    mysql-books              mysql        5.1
                    rabbit-test              rabbitmq     2.4
                    postgresql-eebf5         postgresql   9.0




Tuesday, December 4, 12                                             29
Cloud Foundry - tunnel into a service


                    $ vmc tunnel mongosv-books
                    1: none
                    2: mongo
                    3: mongodump
                    4: mongorestore
                    Which client would you like to start?> 2

                    Opening tunnel on port 10000... OK
                    Waiting for local tunnel to become available... OK
                    MongoDB shell version: 2.0.4
                    connecting to: localhost:10000/db
                    > show collections
                    author
                    book
                    system.indexes
                    system.users
                    >




Tuesday, December 4, 12                                                  30
Cloud Foundry - push app
                  $ vmc push mongosv-web --path target
                  Instances> 1

                  1: spring
                  2: other
                  Framework> spring

                  1: java
                  2: java7
                  3: other
                  Runtime> java7

                  ...
                  Memory Limit> 512M
                  URL> mongosv-web.cloudfoundry.com
                  Create services for application?> n
                  Bind other services to application?> y

                  1: mongosv-books
                  Which service instance?> 1

                  Binding mongosv-books to mongosv-web... OK
                  Bind another service?> n
                  Save configuration?> n

                  Uploading mongosv-web... OK
                  Starting mongosv-web... OK
                  Checking mongosv-web... OK


Tuesday, December 4, 12                                        31
Cloud Foundry - scale app

                    $ vmc scale mongosv-web --instances 2
                    Scaling mongosv-web... OK

                    $ vmc app mongosv-web
                    mongosv-web: running
                      platform: spring on java7
                      usage: 512M × 2 instances
                      urls: mongosv-web.cloudfoundry.com
                      services: mongosv-books




Tuesday, December 4, 12                                     32
Tools
                 • IDE
                          ‣ Cloud Foundry Integration for Eclipse
                            ✓ Spring Tool Suite / Groovy & Grails Tool Suite

                 • Build Tools
                          ‣ Maven plug-in, Gradle plug-in
                 • RAD Tools
                          ‣ Grails (Groovy) + Roo (Spring)

Tuesday, December 4, 12                                                        33
Cloud Foundry Integration for Eclipse




Tuesday, December 4, 12                                34
Maven plug-in
  <plugin>
      <groupId>org.cloudfoundry</groupId>
      <artifactId>cf-maven-plugin</artifactId>
      <version>1.0.0.M4</version>
      <configuration>
           <server>cloudfoundry</server>
           <target>http://api.cloudfoundry.com</target>
           <url>mongosv-web.cloudfoundry.com</url>
           <memory>512</memory>                <profiles>

           <services>                              <profile>
                                                       <id>appfog</id>
               <service>
                                                       <activation>
                   <name>mongosv-books</name>              <activeByDefault>false</activeByDefault>
                   <vendor>mongodb</vendor>            </activation>
                                                       <build>
                   <version>2.0</version>
                                                           <plugins>
               </service>                                      <plugin>
           </services>                                              <groupId>org.cloudfoundry</groupId>
                                                                    <artifactId>cf-maven-plugin</artifactId>
      </configuration>
                                                                    <configuration>
  </plugin>                                                             <server>appfog</server>
                                                                              <target>https://api.appfog.com</target>
                                                                              <url>mongosv-web.aws.af.cm</url>
                                                                              <memory>1024</memory>
                                                                          </configuration>
                                                                      </plugin>
                                                                 </plugins>
                                                             </build>
                                                         </profile>
                                                     </profiles>
Tuesday, December 4, 12                                                                                           35
Maven plug-in configuration
      In your pom.xml:
      <pluginRepositories>
          <pluginRepository>
              <id>repository.springsource.maven.milestone</id>
              <name>Spring Framework Maven Milestone Repository</name>
              <url>http://repo.springsource.org/libs-milestone</url>
          </pluginRepository>
      </pluginRepositories>



                                In ~/.m2/settings.xml:
                                  <servers>
                                    <server>
                                      <id>appfog</id>
                                      <username>cloud@springdeveloper.com</username>
                                      <password>secret</password>
                                    </server>
                                    <server>
                                      <id>cloudfoundry</id>
                                      <username>trisberg@springdeveloper.com</username>
                                      <password>secret</password>
                                    </server>
                                  </servers>

Tuesday, December 4, 12                                                                   36
Deploying Spring MongoDB apps
               to Cloud Foundry & AppFog




                          LIVE DEMO
Tuesday, December 4, 12                        37
Examples ...
                Spring MVC app with MongoTemplate:




       https://github.com/trisberg/mongosv-books/tree/master/mongosv-web
Tuesday, December 4, 12                                                    38
Examples ...
                RESTful Spring MVC app with Repository:




        https://github.com/trisberg/mongosv-books/tree/master/mongosv-rest
Tuesday, December 4, 12                                                      39
News Flash ...




               https://github.com/SpringSource/spring-data-rest
               https://github.com/SpringSource/spring-hateoas
    Gives you basic RESTful access for free - compare to:
    https://github.com/trisberg/mongosv-books/tree/master/
                          mongosv-rest
Tuesday, December 4, 12                                           40
Tuesday, December 4, 12   41
Plans ...




    https://jira.springsource.org/browse/DATAMONGO-584




Tuesday, December 4, 12                                  42
Links
      Spring / Spring Data
             http://www.springsource.org/spring-data/mongodb
             https://jira.springsource.org/browse/DATAMONGO
             https://github.com/SpringSource/rest-shell

      Cloud Foundry
        http://www.cloudfoundry.com/
        https://github.com/cloudfoundry/vcap-java-client/tree/
                   master/cloudfoundry-maven-plugin
       Demos / code examples
              https://github.com/trisberg/mongosv-books
Tuesday, December 4, 12                                          43
Questions?




                          http://www.sxc.hu/photo/860327




Tuesday, December 4, 12                                    44

Weitere ähnliche Inhalte

Was ist angesagt?

MongoDB : The Definitive Guide
MongoDB : The Definitive GuideMongoDB : The Definitive Guide
MongoDB : The Definitive Guide
Wildan Maulana
 

Was ist angesagt? (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
 
MongodB Internals
MongodB InternalsMongodB Internals
MongodB Internals
 
Optimize drupal using mongo db
Optimize drupal using mongo dbOptimize drupal using mongo db
Optimize drupal using mongo db
 
NoSQL databases
NoSQL databasesNoSQL databases
NoSQL databases
 
Mongo db queries
Mongo db queriesMongo db queries
Mongo db queries
 
Mongo DB: Fundamentals & Basics/ An Overview of MongoDB/ Mongo DB tutorials
Mongo DB: Fundamentals & Basics/ An Overview of MongoDB/ Mongo DB tutorialsMongo DB: Fundamentals & Basics/ An Overview of MongoDB/ Mongo DB tutorials
Mongo DB: Fundamentals & Basics/ An Overview of MongoDB/ Mongo DB tutorials
 
Java/Scala Lab: Борис Трофимов - Обжигающая Big Data.
Java/Scala Lab: Борис Трофимов - Обжигающая Big Data.Java/Scala Lab: Борис Трофимов - Обжигающая Big Data.
Java/Scala Lab: Борис Трофимов - Обжигающая Big Data.
 
Mongo db
Mongo dbMongo db
Mongo db
 
Document relations
Document relationsDocument relations
Document relations
 
Conceptos básicos. Seminario web 4: Indexación avanzada, índices de texto y g...
Conceptos básicos. Seminario web 4: Indexación avanzada, índices de texto y g...Conceptos básicos. Seminario web 4: Indexación avanzada, índices de texto y g...
Conceptos básicos. Seminario web 4: Indexación avanzada, índices de texto y g...
 
CouchDB : More Couch
CouchDB : More CouchCouchDB : More Couch
CouchDB : More Couch
 
Mongo db operations_v2
Mongo db operations_v2Mongo db operations_v2
Mongo db operations_v2
 
Mongo DB
Mongo DBMongo DB
Mongo DB
 
Webinar: Back to Basics: Thinking in Documents
Webinar: Back to Basics: Thinking in DocumentsWebinar: Back to Basics: Thinking in Documents
Webinar: Back to Basics: Thinking in Documents
 
Socialite, the Open Source Status Feed Part 2: Managing the Social Graph
Socialite, the Open Source Status Feed Part 2: Managing the Social GraphSocialite, the Open Source Status Feed Part 2: Managing the Social Graph
Socialite, the Open Source Status Feed Part 2: Managing the Social Graph
 
Building your first app with MongoDB
Building your first app with MongoDBBuilding your first app with MongoDB
Building your first app with MongoDB
 
MongoDB : The Definitive Guide
MongoDB : The Definitive GuideMongoDB : The Definitive Guide
MongoDB : The Definitive Guide
 
CouchDB at New York PHP
CouchDB at New York PHPCouchDB at New York PHP
CouchDB at New York PHP
 
MongoDB
MongoDBMongoDB
MongoDB
 
Using MongoDB + Hadoop Together
Using MongoDB + Hadoop TogetherUsing MongoDB + Hadoop Together
Using MongoDB + Hadoop Together
 

Ähnlich wie Thomas risberg mongosv-2012-spring-data-cloud-foundry

Spring Data NHJUG April 2012
Spring Data NHJUG April 2012Spring Data NHJUG April 2012
Spring Data NHJUG April 2012
trisberg
 
MongoSV Schema Workshop
MongoSV Schema WorkshopMongoSV Schema Workshop
MongoSV Schema Workshop
MongoDB
 
springdatajpatwjug-120527215242-phpapp02.pdf
springdatajpatwjug-120527215242-phpapp02.pdfspringdatajpatwjug-120527215242-phpapp02.pdf
springdatajpatwjug-120527215242-phpapp02.pdf
ssuser0562f1
 
Александр Третьяков: "Spring Data JPA and MongoDB"
Александр Третьяков: "Spring Data JPA and MongoDB" Александр Третьяков: "Spring Data JPA and MongoDB"
Александр Третьяков: "Spring Data JPA and MongoDB"
Anna Shymchenko
 
mongodb-120401144140-phpapp01 claud camputing
mongodb-120401144140-phpapp01 claud camputingmongodb-120401144140-phpapp01 claud camputing
mongodb-120401144140-phpapp01 claud camputing
moeincanada007
 

Ähnlich wie Thomas risberg mongosv-2012-spring-data-cloud-foundry (20)

CloudFoundry and MongoDb, a marriage made in heaven
CloudFoundry and MongoDb, a marriage made in heavenCloudFoundry and MongoDb, a marriage made in heaven
CloudFoundry and MongoDb, a marriage made in heaven
 
Spring Data NHJUG April 2012
Spring Data NHJUG April 2012Spring Data NHJUG April 2012
Spring Data NHJUG April 2012
 
Jumpstart: Building Your First MongoDB App
Jumpstart: Building Your First MongoDB AppJumpstart: Building Your First MongoDB App
Jumpstart: Building Your First MongoDB App
 
MongoSV Schema Workshop
MongoSV Schema WorkshopMongoSV Schema Workshop
MongoSV Schema Workshop
 
springdatajpatwjug-120527215242-phpapp02.pdf
springdatajpatwjug-120527215242-phpapp02.pdfspringdatajpatwjug-120527215242-phpapp02.pdf
springdatajpatwjug-120527215242-phpapp02.pdf
 
using Spring and MongoDB on Cloud Foundry
using Spring and MongoDB on Cloud Foundryusing Spring and MongoDB on Cloud Foundry
using Spring and MongoDB on Cloud Foundry
 
MongoDB is the MashupDB
MongoDB is the MashupDBMongoDB is the MashupDB
MongoDB is the MashupDB
 
Introduction To MongoDB
Introduction To MongoDBIntroduction To MongoDB
Introduction To MongoDB
 
No SQL : Which way to go? Presented at DDDMelbourne 2015
No SQL : Which way to go?  Presented at DDDMelbourne 2015No SQL : Which way to go?  Presented at DDDMelbourne 2015
No SQL : Which way to go? Presented at DDDMelbourne 2015
 
NoSQL, which way to go?
NoSQL, which way to go?NoSQL, which way to go?
NoSQL, which way to go?
 
MongoDB
MongoDBMongoDB
MongoDB
 
NoSQL Endgame LWJUG 2021
NoSQL Endgame LWJUG 2021NoSQL Endgame LWJUG 2021
NoSQL Endgame LWJUG 2021
 
Александр Третьяков: "Spring Data JPA and MongoDB"
Александр Третьяков: "Spring Data JPA and MongoDB" Александр Третьяков: "Spring Data JPA and MongoDB"
Александр Третьяков: "Spring Data JPA and MongoDB"
 
Drupal and the rise of the documents
Drupal and the rise of the documentsDrupal and the rise of the documents
Drupal and the rise of the documents
 
Introduction to MongoDB
Introduction to MongoDBIntroduction to MongoDB
Introduction to MongoDB
 
MongoDB - Ruby document store that doesn't rhyme with ouch
MongoDB - Ruby document store that doesn't rhyme with ouchMongoDB - Ruby document store that doesn't rhyme with ouch
MongoDB - Ruby document store that doesn't rhyme with ouch
 
mongodb-120401144140-phpapp01 claud camputing
mongodb-120401144140-phpapp01 claud camputingmongodb-120401144140-phpapp01 claud camputing
mongodb-120401144140-phpapp01 claud camputing
 
Mongo db nosql (1)
Mongo db nosql (1)Mongo db nosql (1)
Mongo db nosql (1)
 
Mongo db php_shaken_not_stirred_joomlafrappe
Mongo db php_shaken_not_stirred_joomlafrappeMongo db php_shaken_not_stirred_joomlafrappe
Mongo db php_shaken_not_stirred_joomlafrappe
 
Using Document Databases with TYPO3 Flow
Using Document Databases with TYPO3 FlowUsing Document Databases with TYPO3 Flow
Using Document Databases with TYPO3 Flow
 

Kürzlich hochgeladen

Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and Myths
Joaquim Jorge
 

Kürzlich hochgeladen (20)

08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men
 
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
 
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
 
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfThe Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
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
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day Presentation
 
GenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdfGenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdf
 
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...
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdf
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and Myths
 
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...
 
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
 
Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organization
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century education
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
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
 
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
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed texts
 

Thomas risberg mongosv-2012-spring-data-cloud-foundry

  • 1. Simplify your MongoDB Java cloud apps with Spring Data Thomas Risberg, Cloud Foundry Team,VMware trisberg@vmware.com @trisberg Spring Data Tuesday, December 4, 12 1
  • 2. About me Currently working on the Cloud Foundry team at VMware • Member of Spring Data Team ‣ Co-author of “Spring Data” from O’Reilly • Joined Spring Framework project in 2003 ‣ Co-author of “Professional Java Development with the Spring Framework” from Wrox Tuesday, December 4, 12 2
  • 3. Introducing - Spring Data • Data access landscape has changed considerably • RDBMS are still important and predominant ‣ but no longer considered a “one size fits all” solution • Spring has always provided excellent data access support ‣ Transaction Management ‣ Portable data access exception hierarchy ‣ JDBC – JdbcTemplate ‣ ORM - Hibernate, JPA, JDO, Ibatis support ‣ Cache support (Spring 3.1) • Spring Data project goal is to “refresh” Spring’s data support Tuesday, December 4, 12 3
  • 4. Spring Data - Mission Statement “ Provide a familiar and consistent Spring-based programming model for Big Data, NoSQL, and relational stores while retaining store-specific features and capabilities. Tuesday, December 4, 12 4
  • 5. Spring Data Supported Technologies: Tuesday, December 4, 12 5
  • 6. Spring Data Repository Spring Data Repository basics: Generic repository implementation Basic CRUD (create, read, update and delete) methods Generating code for queries defined in repository interface findAll findByName ... Pagination and sorting support Currently has JPA and Mongo implementations Tuesday, December 4, 12 6
  • 7. Spring Data CrudRepository • Interface for for a specific type a repository generic CRUD operations on Tuesday, December 4, 12 7
  • 8. Paging and Sorting Repository Paging and Sorting Repository: Extends “CrudRepository” Usage: 8 Tuesday, December 4, 12 8
  • 9. Repository Finders Repository Finder Methods: Keyword examples : Keyword Sample Logical result GreaterThan findByAgeGreaterThan(int age) {"age" : {"$gt" : age}} LessThan findByAgeLessThan(int age) {"age" : {"$lt" : age}} Between findByAgeBetween(int from, int to) {"age" : {"$gt" : from, "$lt" : to}} NotNull findByFirstnameNotNull() {”firstname" : {"$ne" : null}} Null findByFirstnameNull() {”firstname" : null} Like findByFirstnameLike(String pattern) { "firstname" : { "$regex" : "pattern"}} 9 Tuesday, December 4, 12 9
  • 10. MongoDB Repository public interface DeveloperRepository extends MongoRepository<Developer, String> { } MongoRepository extends PagingAndSortingRepository, it’s all free ... 10 Tuesday, December 4, 12 10
  • 11. MongoDB Repository or more control ... public interface BookRepository extends Repository<Book, String> { Book save(Book book); Book findOne(String isbn); void delete(String isbn); List<Book> findAll(); List<Book> findByAuthors(Author author); List<Book> findByPublishedGreaterThan(Date date); List<Book> findByCategoriesIn(String[] categories); List<Book> findByPublishedGreaterThanAndCategoriesIn(Date date, String[] categories); } 11 Tuesday, December 4, 12 11
  • 12. Spring Data and MongoDB Repository App deployed to cloud in 10 steps ... LIVE DEMO https://github.com/trisberg/mongosv-books/tree/master/demo Tuesday, December 4, 12 12
  • 13. MongoTemplate Spring Data support for MongoDB: • MongoTemplate ✓MongoConverter interface for mapping Mongo documents • Built-in Advanced Mapping – Annotation based (@Document, @Id, @DbRef) • MappingMongoConverter for POJO mapping support • Leverage Spring 3.0 TypeConverters and SpEL ✓Exception translation ✓Java based Query, Criteria, and Update DSLs Tuesday, December 4, 12 13
  • 14. Mapping POJOs Annotations for mapping POJOs to documents: • @Document ✓Identifies a domain object to be persisted to MongoDB • @Id ✓Identifies a field should be used as the _id of the document • @Field ✓define custom metadata for document fields ‣ value defines key to be used to store the field in the document ‣ order specifies in which order various fields shall be stored • @DbRef ✓indicates the annotated field is to be stored using a DBRef Tuesday, December 4, 12 14
  • 15. MongoTemplate CRUD Commonly used MongoTemplate methods: • insert(object) ✓Inserts a mapped POJO as a document • save(object) ✓Inserts or updates a mapped POJO as a document • updateFirst(query, update, entityClass) • updateMulti(query, update, entityClass) ✓Executes an update statement for the collection of the entityClass -- either the first or multiple documents matching the query • remove(object) ✓Remove the given object from the collection by id Tuesday, December 4, 12 15
  • 16. MongoTemplate Finders Commonly used MongoTemplate finder methods: • findById(id, entityClass) ✓Returns a document with the given id mapped onto the given entityClass • findOne(query, entityClass) ✓Returns the first document from the results of an ad-hoc query mapped onto the given entityClass • find(query, entityClass) ✓Returns a List of documents from the results of an ad-hoc query mapped onto the given entityClass • findAll(entityClass) ✓Returns a List of documents from the collection used by the entity class mapped onto the given entity class Tuesday, December 4, 12 16
  • 17. Working with queries Commonly used Query and Criteria methods: • searchCriteria = Criteria.where("published").gte(startDate) ✓Creates a Criteria where a field is greater or equal to specified date • searchCriteria.and("categories").in((Object[])categoriesToMatch) ✓adds to the criteria a clause where a fields value included in passed in array of values • Query query = new Query(searchCriteria) ✓Creates a Query based on the Criteria built above. • mongoTemplate.find(query, Book.class) ✓Uses the Query built above to find all book documents that match the Criteria. Tuesday, December 4, 12 17
  • 18. MongoTemplate Example Direct Usage of the Mongo Template: Insert into “Person” Collection findOne using query: { "name" : "Joe"} in db.collection: database.Person Drop collection [database.person] Tuesday, December 4, 12 18
  • 19. Configuration Namespace support for MongoDB <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:mongo="http://www.springframework.org/schema/data/mongo" xsi:schemaLocation="http://www.springframework.org/schema/data/mongo http://www.springframework.org/schema/data/mongo/spring-mongo-1.0.xsd http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.1.xsd"> <bean id="mongoTemplate" class="org.springframework.data.mongodb.core.MongoTemplate"> <constructor-arg name="mongoDbFactory" ref="mongoDbFactory"/> </bean> <mongo:db-factory host="localhost" port="27017" dbname="db"/> </beans> Tuesday, December 4, 12 19
  • 20. Using a custom mapper Create a custom mapper: @Component public class UriWriteConverter implements Converter<URI, DBObject> { public DBObject convert(URI source) { DBObject dbo = new BasicDBObject(); dbo.put("URI", source.toString()); return dbo; } Register it in } your app context: <mongo:mapping-converter id="mongoConverter"> <mongo:custom-converters base-package="org.springframework.data.demo.convert" /> </mongo:mapping-converter> <bean id="mongoTemplate" class="org.springframework.data.mongodb.core.MongoTemplate"> <constructor-arg name="mongoDbFactory" ref="mongoDbFactory" /> <constructor-arg name="mongoConverter" ref="mongoConverter"/> </bean> Tuesday, December 4, 12 20
  • 21. Cloud Foundry configuration Namespace support for MongoDB <dependency>     <groupId>org.cloudfoundry</groupId>     <artifactId>cloudfoundry-runtime</artifactId>     <version>0.8.2</version> </dependency> <repository>     <id>org.springsource.maven.milestone</id>     <name>Spring Framework Maven Milestone Repository</name>     <url>http://repo.springsource.org/libs-milestone</url> </repository> <cloud:mongo-db-factory id="dbFactory" write-concern="SAFE">     <cloud:mongo-options connections-per-host="10" max-wait-time="2000" /> </cloud:mongo-db-factory> Tuesday, December 4, 12 21
  • 23. What is Cloud Foundry? • Cloud Foundry is a PaaS – The application platform will be delivered as a service in the cloud era – The industry calls this platform as a service (PaaS) • PaaS makes it much easier to deploy, run and scale applications • Cloud Foundry - the application platform for the cloud era – Integrated software stack – Application execution engine – Self-service application deployment – Automated application infrastructure provisioning – Curated, updated and operated as a service Tuesday, December 4, 12 23
  • 24. Lots of choices Ap .js pli ce Private ca rfa Data Services tio nte Clouds n rI Se ide rvi Public ov ce Msg Services Pr Clouds Partners Int d ou er .COM fa Cl Micro ce Other Services Clouds Tuesday, December 4, 12 24
  • 25. Many cloud providers Tuesday, December 4, 12 25
  • 26. Cloud Foundry - login & info $ gem install vmc ... $ gem install tunnel-vmc-plugin ... $ vmc target api.cloudfoundry.com Setting target to https://api.cloudfoundry.com... OK $ vmc login trisberg@springdeveloper.com target: https://api.cloudfoundry.com Password> ***** Authenticating... OK $ vmc info VMware's Cloud Application Platform target: https://api.cloudfoundry.com version: 0.999 support: http://support.cloudfoundry.com user: trisberg@springdeveloper.com Tuesday, December 4, 12 26
  • 27. Cloud Foundry - runtimes & frameworks $ vmc info --runtimes --frameworks Getting runtimes... OK Getting frameworks... OK runtime description java 1.6.0_24 java7 1.7.0_04 node 0.4.12 node06 0.6.8 node08 0.8.2 ruby18 1.8.7p357 ruby19 1.9.2p180 framework description grails java_web lift node play rack rails3 sinatra spring standalone Tuesday, December 4, 12 27
  • 28. Cloud Foundry - services $ vmc info --services Getting services... OK service version provider description mongodb 2.0 core MongoDB NoSQL store mysql 5.1 core MySQL database service postgresql 9.0 core PostgreSQL database service (vFabric) rabbitmq 2.4 core RabbitMQ message queue redis 2.2 core Redis key-value store service redis 2.4 core Redis key-value store service redis 2.6 core Redis key-value store service $ vmc services Getting services... OK name service version mongodb-vtoons mongodb 1.8 mysql-books mysql 5.1 rabbit-test rabbitmq 2.4 postgresql-eebf5 postgresql 9.0 Tuesday, December 4, 12 28
  • 29. Cloud Foundry - provision a service $ vmc create-service mongodb mongosv-books Creating service mongosv-books... OK $ vmc services Getting services... OK name service version mongosv-books mongodb 2.0 mongodb-vtoons mongodb 1.8 mysql-books mysql 5.1 rabbit-test rabbitmq 2.4 postgresql-eebf5 postgresql 9.0 Tuesday, December 4, 12 29
  • 30. Cloud Foundry - tunnel into a service $ vmc tunnel mongosv-books 1: none 2: mongo 3: mongodump 4: mongorestore Which client would you like to start?> 2 Opening tunnel on port 10000... OK Waiting for local tunnel to become available... OK MongoDB shell version: 2.0.4 connecting to: localhost:10000/db > show collections author book system.indexes system.users > Tuesday, December 4, 12 30
  • 31. Cloud Foundry - push app $ vmc push mongosv-web --path target Instances> 1 1: spring 2: other Framework> spring 1: java 2: java7 3: other Runtime> java7 ... Memory Limit> 512M URL> mongosv-web.cloudfoundry.com Create services for application?> n Bind other services to application?> y 1: mongosv-books Which service instance?> 1 Binding mongosv-books to mongosv-web... OK Bind another service?> n Save configuration?> n Uploading mongosv-web... OK Starting mongosv-web... OK Checking mongosv-web... OK Tuesday, December 4, 12 31
  • 32. Cloud Foundry - scale app $ vmc scale mongosv-web --instances 2 Scaling mongosv-web... OK $ vmc app mongosv-web mongosv-web: running platform: spring on java7 usage: 512M × 2 instances urls: mongosv-web.cloudfoundry.com services: mongosv-books Tuesday, December 4, 12 32
  • 33. Tools • IDE ‣ Cloud Foundry Integration for Eclipse ✓ Spring Tool Suite / Groovy & Grails Tool Suite • Build Tools ‣ Maven plug-in, Gradle plug-in • RAD Tools ‣ Grails (Groovy) + Roo (Spring) Tuesday, December 4, 12 33
  • 34. Cloud Foundry Integration for Eclipse Tuesday, December 4, 12 34
  • 35. Maven plug-in <plugin> <groupId>org.cloudfoundry</groupId> <artifactId>cf-maven-plugin</artifactId> <version>1.0.0.M4</version> <configuration> <server>cloudfoundry</server> <target>http://api.cloudfoundry.com</target> <url>mongosv-web.cloudfoundry.com</url> <memory>512</memory> <profiles> <services> <profile> <id>appfog</id> <service> <activation> <name>mongosv-books</name> <activeByDefault>false</activeByDefault> <vendor>mongodb</vendor> </activation> <build> <version>2.0</version> <plugins> </service> <plugin> </services> <groupId>org.cloudfoundry</groupId> <artifactId>cf-maven-plugin</artifactId> </configuration> <configuration> </plugin> <server>appfog</server> <target>https://api.appfog.com</target> <url>mongosv-web.aws.af.cm</url> <memory>1024</memory> </configuration> </plugin> </plugins> </build> </profile> </profiles> Tuesday, December 4, 12 35
  • 36. Maven plug-in configuration In your pom.xml: <pluginRepositories> <pluginRepository> <id>repository.springsource.maven.milestone</id> <name>Spring Framework Maven Milestone Repository</name> <url>http://repo.springsource.org/libs-milestone</url> </pluginRepository> </pluginRepositories> In ~/.m2/settings.xml: <servers> <server> <id>appfog</id> <username>cloud@springdeveloper.com</username> <password>secret</password> </server> <server> <id>cloudfoundry</id> <username>trisberg@springdeveloper.com</username> <password>secret</password> </server> </servers> Tuesday, December 4, 12 36
  • 37. Deploying Spring MongoDB apps to Cloud Foundry & AppFog LIVE DEMO Tuesday, December 4, 12 37
  • 38. Examples ... Spring MVC app with MongoTemplate: https://github.com/trisberg/mongosv-books/tree/master/mongosv-web Tuesday, December 4, 12 38
  • 39. Examples ... RESTful Spring MVC app with Repository: https://github.com/trisberg/mongosv-books/tree/master/mongosv-rest Tuesday, December 4, 12 39
  • 40. News Flash ... https://github.com/SpringSource/spring-data-rest https://github.com/SpringSource/spring-hateoas Gives you basic RESTful access for free - compare to: https://github.com/trisberg/mongosv-books/tree/master/ mongosv-rest Tuesday, December 4, 12 40
  • 42. Plans ... https://jira.springsource.org/browse/DATAMONGO-584 Tuesday, December 4, 12 42
  • 43. Links Spring / Spring Data http://www.springsource.org/spring-data/mongodb https://jira.springsource.org/browse/DATAMONGO https://github.com/SpringSource/rest-shell Cloud Foundry http://www.cloudfoundry.com/ https://github.com/cloudfoundry/vcap-java-client/tree/ master/cloudfoundry-maven-plugin Demos / code examples https://github.com/trisberg/mongosv-books Tuesday, December 4, 12 43
  • 44. Questions? http://www.sxc.hu/photo/860327 Tuesday, December 4, 12 44