【IT168 專稿】當前,NOSQL時代其實已經來臨,在NOSQL的大家族中,MongoDB以其可擴展性強,性能高以及開源佔據了重要的地位。在MongoDB中,存儲數據的方式不再是關係型資料庫,而是以象JSON格式那樣進行存儲,所以可以稱為文檔型的NOSQL。本文將以一個實際的例子,介紹如何運用Spring開源框架下的Spring Data數據存取框架結合MongoDB,創建一個簡單的CRUD應用(增刪改查)。本文要求讀者有一定的MongoDB和Spring的基礎知識。
關於Spring Data For MongoDB
大家對Spring 框架應該是相當熟悉了,而Spring data 則是spring新推出的一套方便開發者對關係資料庫以及NOSQL進行存取開發的基於spring的API框架。而其中的一個分支Spring Data for MongoDB則是專門為MongoDB度身訂造的用於方便開發者對MongoDB進行操作的一組API。如果開發者熟悉Spring開發的話,則可以很容易地使用Spring Data for MongoDB進行開發。在Spring Data For MongoDB中,比如封裝了MongoTemplate,這個模板工具類有點象JDBCTemplate工具類,可以很方便地進行MongoDB的常用操作。它其中包括能在文檔對象和POJO中做對應的關聯映射,還有異常的封裝都跟spring是一個體系的,而且對對象的查詢更新等,都可以依舊使用開發者熟悉的比如Query,Criteria等進行資料庫的查詢等操作,此外,還可以使用JPA對MongoDB進行操作。開發者可以在如下的地址下載Spring for MongoDB:http://www.springsource.org/download/community
安裝MongoDB
下面我們快速安裝MongoDB,如果用戶已經熟悉如何安裝MongoDB,則可以跳過本小節,直接進入下一小節。
c:\mongodb\bin\mongod.exe –dbpath c:\mongodb\data\db
1) 下載最新版本的MongoDB,解壓縮到某個目錄,比如c:\mongodb
2) mongodb需要一個目錄去存放數據,mongodb默認的數據存放目錄為c:\data\db,但我們可以隨意指定目錄去存放數據,這裡我們指定c:\mongodb\data\db去存放數據。
3) 接下來是啟動的工作,到命令行方式下輸入如下指令:
c:\mongodb\bin\mongod.exe –dbpath c:\mongodb\data\db
要注意的是,如果路徑中含有空格,則需要使用雙引號包括起來,如:
c:\mongodb\bin\mongod.exe –dbpath「c:\mongodb\data\db store place」
如果要以服務的形式在windows中啟動,請參考下面地址中的介紹:
http://docs.mongodb.org/manual/tutorial/install-mongodb-on-windows/
使用Spring Data For Mongodb創建應用
接下來,我們開始創建一個簡單的CRUD功能的JAVA應用,首先要在工程的lib目錄下,添加上Spring Data For Mongodb中相關的lib包。我們將工程命名為NatureStore,
步驟1 創建POJO
代碼如下:
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 + "]";
}
}
這裡創建了一個Tree的POJO,並且充分使用了Spring 的註解功能,可以看到,
@Document註解,表示這個POJO最終要持久化為MongoDB中的document,@id
指出了需要持久化的@id。
${PageNumber}
步驟2 創建接口
下面創建關於新增,刪除,查詢獲取的相關接口,代碼如下:
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);
//根據id獲得對象
public T getObject(String id);
//更新
public WriteResult updateObject(String id, String name);
//刪除對象
public void deleteObject(String id);
//創建collection
public void createCollection();
//刪除collection
public void dropCollection();
}
步驟3 創建接口的實現類
下面就是充分利用MongoDB Template模板工具類,來實現對collection的初始化,並且實現了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;
}
/**
* 獲得所有的tree
*/
public List<Tree> getAllObjects() {
return mongoTemplate.findAll(Tree.class);
}
/**
*保存一個tree對象
*/
public void saveObject(Tree tree) {
mongoTemplate.insert(tree);
}
/**
* 通過id進行查找
*/
public Tree getObject(String id) {
return mongoTemplate.findOne(new Query(Criteria.where("id").is(id)),
Tree.class);
}
/**
*根據id和name進行查找
*/
public WriteResult updateObject(String id, String name) {
return mongoTemplate.updateFirst(
new Query(Criteria.where("id").is(id)),
Update.update("name", name), Tree.class);
}
/**
* 根據id刪除tree
*/
public void deleteObject(String id) {
mongoTemplate
.remove(new Query(Criteria.where("id").is(id)), Tree.class);
}
/**
* 如果collection不存在則建立
*/
public void createCollection() {
if (!mongoTemplate.collectionExists(Tree.class)) {
mongoTemplate.createCollection(Tree.class);
}
}
/**
* 如果collection存在則刪除之
*/
public void dropCollection() {
if (mongoTemplate.collectionExists(Tree.class)) {
mongoTemplate.dropCollection(Tree.class);
}
}
}
${PageNumber}
步驟4 配置spring data for MongoDB
還要在spring的配置文件中,進行配置spring data for 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>
<!—配置mongo的ip,埠-->
<bean id="mongo" class="org.springframework.data.mongodb.core.MongoFactoryBean">
<property name="host" value="localhost" />
<property name="port" value="27017" />
</bean>
<context:annotation-config />
<context:component-scan base-package="com.orangeslate.naturestore">
<context:exclude-filter type="annotation"
expression="org.springframework.context.annotation.Configuration" />
</context:component-scan>
</beans>
在上面的配置文件中,通過註解,配置了MongoDB的IP和埠,以及MongoDB template的實例。
步驟5 創建測試用例
最後編寫一個測試用例進行測試,代碼如下:
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);
// 插入之前先刪除collection
repository.dropCollection();
// 創建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());
}
}
最後輸出結果如下:
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]]
分別演示了插入,刪除和查找記錄。
本文完整代碼可以在如下地址下載:
https://github.com/lijinjoseji/NatureStore/blob/master/NatureStore.zip