使用MongoDB和Spring Data創建一個簡單的Java 的CRUD應用

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

 

Spring Data for MongoDB

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

五步安裝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

    如果你的路徑包含空格,請使用雙引號引起來。

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

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

五步使用Spring Data創建一個應用。

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

最後,讓我們以Java應用程序的方式運行這個示例,我們可以看到如下的輸出。第一個方法存儲了一個"Apple Tree"。第二個方法存儲了一個"Orange Tree"。第三個方法通過id獲取一個對象。第四個使用Peach Tree更新對象。最後一個方法刪除了第二個對象。

1 1. [Person [ id =1, name=Apple Tree, age=10, category=null]]
2 2. [Person [ id =1, name=Apple Tree, age=10, category=null], Person [ id =2, name=Orange Tree, age=3, category=null]]
3 Tree with id 1Person [ id =1, name=Apple Tree, age=10, category=null]
4 3. [Person [ id =1, name=Peach Tree, age=10, category=null], Person [ id =2, name=Orange Tree, age=3, category=null]]
5 4. [Person [ id =1, name=Peach Tree, age=10, category=null]]

注:可以在GitHub上下載到源碼

OSChina.NET 原創翻譯/原文鏈接

 

http://www.oschina.net/question/82993_61815?from=20120729

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章