ITeye博客

使用MongoDB和Spring Data创建一个简单的Java 的CRUD应用

ttaale · 2012-08-01 09:57 · java综合 · 编程语言 · Markdown

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

评论(0)

暂无评论。

评论功能维护中,当前仅展示历史评论。