`

使用Spring Data来操作MongoDB

 
阅读更多

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。
    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) {
     
            ConfigurableApplicationContext context = new ClassPathXmlApplicationContext(
                    "classpath:/spring/applicationContext.xml");
     
            Repository repository = context.getBean(NatureRepositoryImpl.class);
     
            // cleanup collection before insertion
            repository.dropCollection();
     
            // create collection
            repository.createCollection();
     
            repository.saveObject(new Tree("1""Apple Tree"10));
     
            System.out.println("1. " + repository.getAllObjects());
     
            repository.saveObject(new Tree("2""Orange Tree"3));
     
            System.out.println("2. " + repository.getAllObjects());
     
            System.out.println("Tree with id 1" + repository.getObject("1"));
     
            repository.updateObject("1""Peach Tree");
     
            System.out.println("3. " + repository.getAllObjects());
     
            repository.deleteObject("2");
     
            System.out.println("4. " + repository.getAllObjects());
        }
    }

最后,让我们以Java应用程序的方式运行这个示例,我们可以看到如下的输出。第一个方法存储了一个"Apple Tree"。第二个方法存储了一个"Orange Tree"。第三个方法通过id获取一个对象。第四个使用Peach Tree更新对象。最后一个方法删除了第二个对象。

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

注:可以在GitHub上下载到源码

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics