使用Spring Data來操做MongoDB

http://www.open-open.com/lib/view/open1342877356974.htmlhtml

 MongoDB 是一個可擴展的、高性能的、開源的NoSQL數據庫,跟傳統的數據庫不同,MongoDB並非將數據存儲在表中,他將數據結構化爲一個相似於JSON的文檔中。這篇文章就是展現如何使用Java基於MongoDB和Spring Data建立一個CRUD應用。 
java

 

Spring Data for MongoDBgit

Spring Data for MongoDB提供了一個相似於基於Sping編程模型的NoSQL數據存儲。Spring Data for MongoDB提供了不少特性,它使不少MongoDB的Java開發者解放了不少。MongoTemplate helper類支持通用的Mongo操做。它整合了文檔和POJO之間的對象映射。一般,他會轉換數據庫訪問異常到Spring中的異常結構。使用起來很是的方便。
你能夠點擊這裏下載。github

五步安裝MongoDBspring

最清楚的安裝步驟固然是MongoDB官方的安裝說明了。安裝說明。mongodb

  1. 下載最新的MongoDB。
  2. 解壓到指定目錄(這也算一步...)
  3. MongoDB須要一個存儲文件的地方,Windows下默認的路徑是C:\data\db。可是咱們能夠指定。例如我指定下面的路徑
    ?
    1
    <strong>C:\mongodb\data\db< /strong >
  4. 到C:\mongodb\bin 文件夾下執行以下命令。
    ?
    1
    C:\mongodb\bin\mongod.exe –dbpath C:\mongodb\data\db

    若是你的路徑包含空格,請使用雙引號引發來。shell

  5. 到C:\mongodb\bin文件夾下,執行mongo.exe。默認的,mongo腳本將會監聽localhost的27017端口。若是想將MongoDB做爲windows的服務運行,點擊這裏。

到這裏MongoDB的安裝就完成了,接下來使用java搞CRUD。數據庫

五步使用Spring Data建立一個應用。express

  1. 使用@Document註解指明一個領域對象將被持久化到MongoDB中。@Id註解identifies。
    ?
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    package com.orangeslate.naturestore.domain;
     
    import org.springframework.data.annotation.Id;
    import org.springframework.data.mongodb.core.mapping.Document;
     
    @Document
    public class Tree {
     
         @Id
         private String id;
     
         private String name;
     
         private String category;
     
         private int age;
     
         public Tree(String id, String name,  int age) {
             this .id = id;
             this .name = name;
             this .age = age;
         }
     
         public String getId() {
             return id;
         }
     
         public void setId(String id) {
             this .id = id;
         }
     
         public String getName() {
             return name;
         }
     
         public void setName(String name) {
             this .name = name;
         }
     
         public String getCategory() {
             return category;
         }
     
         public void setCategory(String category) {
             this .category = category;
         }
     
         public int getAge() {
             return age;
         }
     
         public void setAge( int age) {
             this .age = age;
         }
     
         @Override
         public String toString() {
             return "Person [id=" + id +  ", name=" + name +  ", age=" + age
                     ", category=" + category +  "]" ;
         }
    }
  2. 建立一個簡單的接口。建立一個簡單的接口,這個接口帶有CRUD方法。這裏我還帶有createCollection方法和dropCollection方法。
    ?
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    package com.orangeslate.naturestore.repository;
     
    import java.util.List;
     
    import com.mongodb.WriteResult;
     
    public interface Repository<T> {
     
         public List<T> getAllObjects();
     
         public void saveObject(T object);
     
         public T getObject(String id);
     
         public WriteResult updateObject(String id, String name);
     
         public void deleteObject(String id);
     
         public void createCollection();
     
         public void dropCollection();
    }
  3. 建立一個指定的領域對象CRUD的實現。
    ?
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    70
    71
    72
    73
    74
    75
    76
    77
    78
    package com.orangeslate.naturestore.repository;
     
    import java.util.List;
     
    import org.springframework.data.mongodb.core.MongoTemplate;
    import org.springframework.data.mongodb.core.query.Criteria;
    import org.springframework.data.mongodb.core.query.Query;
    import org.springframework.data.mongodb.core.query.Update;
     
    import com.mongodb.WriteResult;
    import com.orangeslate.naturestore.domain.Tree;
     
    public class NatureRepositoryImpl  implements Repository<Tree> {
     
         MongoTemplate mongoTemplate;
     
         public void setMongoTemplate(MongoTemplate mongoTemplate) {
             this .mongoTemplate = mongoTemplate;
         }
     
         /**
          * Get all trees.
          */
         public List<Tree> getAllObjects() {
             return mongoTemplate.findAll(Tree. class );
         }
     
         /**
          * Saves a {<span class="referer">@link</span>  Tree}.
          */
         public void saveObject(Tree tree) {
             mongoTemplate.insert(tree);
         }
     
         /**
          * Gets a {<span class="referer">@link</span>  Tree} for a particular id.
          */
         public Tree getObject(String id) {
             return mongoTemplate.findOne( new Query(Criteria.where( "id" ).is(id)),
                     Tree. class );
         }
     
         /**
          * Updates a {<span class="referer">@link</span>  Tree} name for a particular id.
          */
         public WriteResult updateObject(String id, String name) {
             return mongoTemplate.updateFirst(
                     new Query(Criteria.where( "id" ).is(id)),
                     Update.update( "name" , name), Tree. class );
         }
     
         /**
          * Delete a {<span class="referer">@link</span>  Tree} for a particular id.
          */
         public void deleteObject(String id) {
             mongoTemplate
                     .remove( new Query(Criteria.where( "id" ).is(id)), Tree. class );
         }
     
         /**
          * Create a {<span class="referer">@link</span>  Tree} collection if the collection does not already
          * exists
          */
         public void createCollection() {
             if (!mongoTemplate.collectionExists(Tree. class )) {
                 mongoTemplate.createCollection(Tree. class );
             }
         }
     
         /**
          * Drops the {<span class="referer">@link</span>  Tree} collection if the collection does already exists
          */
         public void dropCollection() {
             if (mongoTemplate.collectionExists(Tree. class )) {
                 mongoTemplate.dropCollection(Tree. class );
             }
         }
    }
  4. 建立Spring context。將全部spring beans和mongodb對象都聲明在Spring context文件中,這裏建立的是applicationContext.xml文件。注意到咱們並無建立一個叫作"nature"的數據庫。在第一次存儲數據的時候MongoDB將會爲咱們建立這個數據庫。
    ?
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    <? xml version = "1.0" encoding = "UTF-8" ?>
    < beans xmlns = "http://www.springframework.org/schema/beans"
         xmlns:xsi = "http://www.w3.org/2001/XMLSchema-instance" xmlns:context = "http://www.springframework.org/schema/context"
         xsi:schemaLocation="http://www.springframework.org/schema/beans
     
    http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
     
     
    http://www.springframework.org/schema/context
     
             http://www.springframework.org/schema/context/spring-context-3.0.xsd">
     
         < bean id = "natureRepository"
             class = "com.orangeslate.naturestore.repository.NatureRepositoryImpl" >
             < property name = "mongoTemplate" ref = "mongoTemplate" />
         </ bean >
     
         < bean id = "mongoTemplate" class = "org.springframework.data.mongodb.core.MongoTemplate" >
             < constructor-arg name = "mongo" ref = "mongo" />
             < constructor-arg name = "databaseName" value = "nature" />
         </ bean >
     
         <!-- Factory bean that creates the Mongo instance -->
         < bean id = "mongo" class = "org.springframework.data.mongodb.core.MongoFactoryBean" >
             < property name = "host" value = "localhost" />
             < property name = "port" value = "27017" />
         </ bean >
     
         <!-- Activate annotation configured components -->
         < context:annotation-config />
     
         <!-- Scan components for annotations within the configured package -->
         < context:component-scan base-package = "com.orangeslate.naturestore" >
             < context:exclude-filter type = "annotation"
                 expression = "org.springframework.context.annotation.Configuration" />
         </ context:component-scan >
     
    </ beans >
  5. 建立一個測試類。這裏我已經建立了一個測試類,並經過ClassPathXmlApplicationContext來初始化他。
    ?
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    package com.orangeslate.naturestore.test;
     
    import org.springframework.context.ConfigurableApplicationContext;
    import org.springframework.context.support.ClassPathXmlApplicationContext;
     
    import com.orangeslate.naturestore.domain.Tree;
    import com.orangeslate.naturestore.repository.NatureRepositoryImpl;
    import com.orangeslate.naturestore.repository.Repository;
     
    public class MongoTest {
     
         public static void main(String[] args) {
相關文章
相關標籤/搜索