使用Spring Data來操作MongoDB

jopen 12年前發布 | 188K 次閱讀 MongoDB NoSQL數據庫

    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。但是我們可以指定。例如我指定下面的路徑
    C:\mongodb\data\db
  4. 到C:\mongodb\bin 文件夾下執行如下命令。
    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。
    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方法。
    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的實現。
    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 {@link  Tree}.
         */
        public void saveObject(Tree tree) {
            mongoTemplate.insert(tree);
        }
    
        /**
         * Gets a {@link  Tree} for a particular id.
         */
        public Tree getObject(String id) {
            return mongoTemplate.findOne(new Query(Criteria.where("id").is(id)),
                    Tree.class);
        }
    
        /**
         * Updates a {@link  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 {@link  Tree} for a particular id.
         */
        public void deleteObject(String id) {
            mongoTemplate
                    .remove(new Query(Criteria.where("id").is(id)), Tree.class);
        }
    
        /**
         * Create a {@link  Tree} collection if the collection does not already
         * exists
         */
        public void createCollection() {
            if (!mongoTemplate.collectionExists(Tree.class)) {
                mongoTemplate.createCollection(Tree.class);
            }
        }
    
        /**
         * Drops the {@link  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將會為我們創建這個數據庫。
    <?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來初始化他。
    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. [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上下載到源碼

 本文由用戶 jopen 自行上傳分享,僅供網友學習交流。所有權歸原作者,若您的權利被侵害,請聯系管理員。
 轉載本站原創文章,請注明出處,并保留原始鏈接、圖片水印。
 本站是一個以用戶分享為主的開源技術平臺,歡迎各類分享!