MongoDB整合Spring 詳細講解(含代碼)

寫這篇文章也做了下思考,首先是本人技術欠佳。但就是喜歡研究一些東西。因爲在此之前有很多的朋友已經寫過類似的,很多我也看過,但是講解的不夠深入。對有些朋友提出的問題不能給出答案。在這裏,我根據我目前的能力對其進行整理。並最終運行成功。

在測試過程中出現過一下問題:

1、org/springframework/data/mapping/context/MappingContextAware

2、src-resolve: Cannot resolve the name 'repository:repository' to a(n) 'type definition'

以上都是版本不匹配引起的。特別是第二個錯誤我看有些解決時候提到了jpa,但是我這裏沒有使用jpa後來我是把spring-data-commons的包替換了個版本就不出現了。

我先說下我的開發環境:

myeclipse 6.5

mongodb 2.0.8

spring 3.0.4 

最後就是下面2個(這兩個版本不對就容易出現各種各樣的,雜七雜八的問題) 這裏我就給出我所採用的版本

spring-data-document

spring-data-commons

有所改變所有版本必須要對應好下面是jar下載地址 
http://www.springsource.org/spring-data/mongodb 
http://www.springsource.org/spring-data/commons

下載版本分別爲:

spring-data-commons-dist-1.4.0.M1

spring-data-document-1.0.0.M2.zip
下面給出我工程的圖片

 

然後就開始我們開發之旅吧!

首先新建application.xml配置文件

[html] view plaincopy
  1. <span style="font-size:18px;color:#3366ff;"><?xml version="1.0" encoding="UTF-8"?>  
  2. <beans xmlns="http://www.springframework.org/schema/beans"    
  3.           xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"    
  4.           xmlns:context="http://www.springframework.org/schema/context"    
  5.           xmlns:mongo="http://www.springframework.org/schema/data/mongo"    
  6.           xsi:schemaLocation="http://www.springframework.org/schema/context     
  7.           http://www.springframework.org/schema/context/spring-context-3.0.xsd     
  8.           http://www.springframework.org/schema/data/mongo     
  9.           http://www.springframework.org/schema/data/mongo/spring-mongo-1.0.xsd     
  10.           http://www.springframework.org/schema/beans     
  11.           http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">     
  12.       
  13.         <mongo:mongo host="192.168.0.138" port="27017"/>  
  14.           
  15.           
  16.       
  17.        <bean id="mongoTemplate" class="org.springframework.data.document.mongodb.MongoTemplate">     
  18.         <constructor-arg ref="mongo"/>     
  19.         <constructor-arg name="databaseName" value="db"/>     
  20.         <constructor-arg name="defaultCollectionName" value="person" />     
  21.       </bean>     
  22.       
  23.      <bean id="personRepository" class="com.mongo.dao.impl.PersonRepository">     
  24.         <property name="mongoTemplate" ref="mongoTemplate"></property>     
  25.     </bean>     
  26.       
  27.      <context:annotation-config />  
  28.           
  29. </beans>   
  30.     </span>  


然後編寫操作mongodb的接口

[java] view plaincopy
  1. <span style="font-size:18px;color:#3366ff;">/** 
  2.  * AbstractRepository.java 
  3.  * 版權所有(C) 2012  
  4.  * 創建:cuiran 2012-12-12 11:40:40 
  5.  */  
  6. package com.mongo.dao;  
  7.   
  8. import java.util.List;  
  9.   
  10. import com.mongo.bean.Person;  
  11.   
  12. /** 
  13.  * TODO 
  14.  * @author cuiran 
  15.  * @version TODO 
  16.  */  
  17. public interface AbstractRepository {  
  18.       
  19.     /** 
  20.      *  
  21.      *<b>function:</b>添加對象 
  22.      * @author cuiran 
  23.      * @createDate 2012-12-12 11:41:30 
  24.      */  
  25.     public void insert(Person person);   
  26.       
  27.     /** 
  28.      *  
  29.      *<b>function:</b>根據ID查找對象 
  30.      * @author cuiran 
  31.      * @createDate 2012-12-12 11:41:41 
  32.      */  
  33.     public Person findOne(String id);     
  34.     /** 
  35.      *  
  36.      *<b>function:</b>查詢所有 
  37.      * @author cuiran 
  38.      * @createDate 2012-12-12 16:26:06 
  39.      */  
  40.     public List<Person> findAll();     
  41.       
  42.     public List<Person> findByRegex(String regex);  
  43.     /** 
  44.      *  
  45.      *<b>function:</b>刪除指定的ID對象 
  46.      * @author cuiran 
  47.      * @createDate 2012-12-12 16:26:16 
  48.      */  
  49.     public void removeOne(String id);     
  50.     /** 
  51.      *  
  52.      *<b>function:</b>刪除所有 
  53.      * @author cuiran 
  54.      * @createDate 2012-12-12 16:25:40 
  55.      */  
  56.     public void removeAll();     
  57.     /** 
  58.      * 通過ID找到並修改 
  59.      *<b>function:</b> 
  60.      * @author cuiran 
  61.      * @createDate 2012-12-12 16:25:51 
  62.      */  
  63.     public void findAndModify(String id);     
  64.   
  65.       
  66. }  
  67. </span>  


再寫對應接口的實現類:

[java] view plaincopy
  1. <span style="font-size:18px;color:#3366ff;">/** 
  2.  * PersonRepository.java 
  3.  * 版權所有(C) 2012  
  4.  * 創建:cuiran 2012-12-12 11:42:51 
  5.  */  
  6. package com.mongo.dao.impl;  
  7.   
  8. import java.util.List;  
  9. import java.util.regex.Pattern;  
  10.   
  11. import org.springframework.data.document.mongodb.MongoTemplate;  
  12. import org.springframework.data.document.mongodb.query.Criteria;  
  13. import org.springframework.data.document.mongodb.query.Query;  
  14. import org.springframework.data.document.mongodb.query.Update;  
  15. import com.mongo.bean.Person;  
  16. import com.mongo.dao.AbstractRepository;  
  17.   
  18. /** 
  19.  * TODO 
  20.  * @author cuiran 
  21.  * @version TODO 
  22.  */  
  23. public class PersonRepository implements AbstractRepository {  
  24.   
  25.       private MongoTemplate mongoTemplate;     
  26.   
  27.     /* (non-Javadoc) 
  28.      * @see com.mongo.dao.AbstractRepository#findAll() 
  29.      */  
  30.     @Override  
  31.     public List<Person> findAll() {  
  32.         // TODO Auto-generated method stub  
  33.         return getMongoTemplate().find(new Query(), Person.class);     
  34.   
  35.     }  
  36.   
  37.     /* (non-Javadoc) 
  38.      * @see com.mongo.dao.AbstractRepository#findAndModify(java.lang.String) 
  39.      */  
  40.     @Override  
  41.     public void findAndModify(String id) {  
  42.         // TODO Auto-generated method stub  
  43.         //new Query(Criteria.where("id").is(id)), new Update().inc("age", 3)  
  44.           
  45.         getMongoTemplate().updateFirst(new Query(Criteria.where("id").is(id)), new Update().inc("age"3));  
  46.   
  47.     }  
  48.   
  49.     /* (non-Javadoc) 
  50.      * @see com.mongo.dao.AbstractRepository#findByRegex(java.lang.String) 
  51.      */  
  52.     @Override  
  53.     public List<Person> findByRegex(String regex) {  
  54.         // TODO Auto-generated method stub  
  55.          Pattern pattern = Pattern.compile(regex,Pattern.CASE_INSENSITIVE);     
  56.           Criteria criteria = new Criteria("name").regex(pattern.toString());     
  57.             return getMongoTemplate().find(new Query(criteria), Person.class);     
  58.   
  59.     }  
  60.   
  61.     /* (non-Javadoc) 
  62.      * @see com.mongo.dao.AbstractRepository#findOne(java.lang.String) 
  63.      */  
  64.     @Override  
  65.     public Person findOne(String id) {  
  66.         // TODO Auto-generated method stub  
  67.          return getMongoTemplate().findOne(new Query(Criteria.where("id").is(id)), Person.class);     
  68.   
  69.     }  
  70.   
  71.     /* (non-Javadoc) 
  72.      * @see com.mongo.dao.AbstractRepository#insert(com.mongo.bean.Person) 
  73.      */  
  74.     @Override  
  75.     public void insert(Person person) {  
  76.         // TODO Auto-generated method stub  
  77.         getMongoTemplate().insert(person);     
  78.     }  
  79.   
  80.     /* (non-Javadoc) 
  81.      * @see com.mongo.dao.AbstractRepository#removeAll() 
  82.      */  
  83.     @Override  
  84.     public void removeAll() {  
  85.         // TODO Auto-generated method stub  
  86.         List<Person> list = this.findAll();     
  87.         if(list != null){     
  88.             for(Person person : list){     
  89.                 getMongoTemplate().remove(person);     
  90.             }     
  91.         }     
  92.   
  93.     }  
  94.   
  95.     /* (non-Javadoc) 
  96.      * @see com.mongo.dao.AbstractRepository#removeOne(java.lang.String) 
  97.      */  
  98.     @Override  
  99.     public void removeOne(String id) {  
  100.         // TODO Auto-generated method stub  
  101.         Criteria criteria = Criteria.where("id").in(id);     
  102.         if(criteria == null){     
  103.              Query query = new Query(criteria);     
  104.              if(query != null && getMongoTemplate().findOne(query, Person.class) != null)     
  105.                  getMongoTemplate().remove(getMongoTemplate().findOne(query, Person.class));     
  106.         }     
  107.   
  108.     }  
  109.   
  110.     /** 
  111.      * @return the mongoTemplate 
  112.      */  
  113.     public MongoTemplate getMongoTemplate() {  
  114.         return mongoTemplate;  
  115.     }  
  116.   
  117.     /** 
  118.      * @param mongoTemplate the mongoTemplate to set 
  119.      */  
  120.     public void setMongoTemplate(MongoTemplate mongoTemplate) {  
  121.         this.mongoTemplate = mongoTemplate;  
  122.     }  
  123.   
  124. }  
  125. </span>  

這裏也給出對應Person對象代碼

[java] view plaincopy
  1. <span style="font-size:18px;color:#3366ff;">/** 
  2.  * Person.java 
  3.  * 版權所有(C) 2012  
  4.  * 創建:cuiran 2012-12-12 11:37:16 
  5.  */  
  6. package com.mongo.bean;  
  7.   
  8. import java.io.Serializable;  
  9.   
  10. /** 
  11.  * TODO 
  12.  * @author cuiran 
  13.  * @version TODO 
  14.  */  
  15. public class Person implements Serializable {  
  16.   
  17.     /** 
  18.      *  
  19.      */  
  20.     private static final long serialVersionUID = 3617931430808763429L;  
  21.       
  22.     private String id;     
  23.     private String name;     
  24.     private int age;  
  25.     public Person() {  
  26.         super();  
  27.     }  
  28.     public Person(String id, String name, int age) {  
  29.         super();  
  30.         this.id = id;  
  31.         this.name = name;  
  32.         this.age = age;  
  33.     }  
  34.     /** 
  35.      * @return the id 
  36.      */  
  37.     public String getId() {  
  38.         return id;  
  39.     }  
  40.     /** 
  41.      * @param id the id to set 
  42.      */  
  43.     public void setId(String id) {  
  44.         this.id = id;  
  45.     }  
  46.     /** 
  47.      * @return the name 
  48.      */  
  49.     public String getName() {  
  50.         return name;  
  51.     }  
  52.     /** 
  53.      * @param name the name to set 
  54.      */  
  55.     public void setName(String name) {  
  56.         this.name = name;  
  57.     }  
  58.     /** 
  59.      * @return the age 
  60.      */  
  61.     public int getAge() {  
  62.         return age;  
  63.     }  
  64.     /** 
  65.      * @param age the age to set 
  66.      */  
  67.     public void setAge(int age) {  
  68.         this.age = age;  
  69.     }  
  70.     /** 
  71.      *  
  72.      * @param name 
  73.      * @param age 
  74.      */  
  75.     public Person(String name, int age) {  
  76.         super();  
  77.         this.name = name;  
  78.         this.age = age;  
  79.     }     
  80.   
  81.      public String toString() {     
  82.             return "Person[id="+id+",name="+name+",age="+age+"]";     
  83.         }     
  84.   
  85.   
  86. }  
  87. </span>  

最後寫出我們的測試類開始進行測試

[java] view plaincopy
  1. <span style="font-size:18px;color:#3366ff;">/** 
  2.  * MongoTest.java 
  3.  * 版權所有(C) 2012  
  4.  * 創建:cuiran 2012-12-12 11:54:30 
  5.  */  
  6. package com.mongo.test;  
  7.   
  8. import java.util.List;  
  9.   
  10. import org.apache.commons.logging.Log;  
  11. import org.apache.commons.logging.LogFactory;  
  12. import org.springframework.context.ApplicationContext;  
  13. import org.springframework.context.support.ClassPathXmlApplicationContext;  
  14.   
  15. import com.mongo.bean.Person;  
  16. import com.mongo.dao.AbstractRepository;  
  17. import com.mongo.dao.impl.PersonRepository;  
  18.   
  19.   
  20.   
  21. /** 
  22.  * TODO 
  23.  * @author cuiran 
  24.  * @version TODO 
  25.  */  
  26. public class MongoTest {  
  27.   
  28.     private static Log log = LogFactory.getLog(MongoTest.class.getName());  
  29.       
  30.     private  AbstractRepository pr=null;  
  31.       
  32.     /** 
  33.      *  
  34.      *<b>function:</b> 
  35.      * @author cuiran 
  36.      * @createDate 2012-12-12 16:08:02 
  37.      */  
  38.     public void init(){  
  39.          log.debug("開始啓動");  
  40.          ApplicationContext ctx = new ClassPathXmlApplicationContext("applicationContext.xml");  
  41.           pr= (PersonRepository)ctx.getBean("personRepository");  
  42.            
  43.           
  44.           
  45.     }  
  46.     /** 
  47.      *  
  48.      *<b>function:</b>添加 
  49.      * @author cuiran 
  50.      * @createDate 2012-12-12 16:11:01 
  51.      */  
  52.     public void insert(){  
  53.           
  54.         Person p=new Person("cuiran",27);  
  55.          pr.insert(p);  
  56.          log.debug("添加成功");  
  57.     }  
  58.     /** 
  59.      *  
  60.      *<b>function:</b>根據輸入的ID查找對象 
  61.      * @author cuiran 
  62.      * @createDate 2012-12-12 16:24:10 
  63.      */  
  64.     public void findOne(){  
  65.         String id="50c83cb552c2ceb0463177d6";  
  66.         Person p= pr.findOne(id);  
  67.         log.debug(p);  
  68.     }  
  69.       
  70.       
  71.     /** 
  72.      *  
  73.      *<b>function:</b>查詢所有 
  74.      * @author cuiran 
  75.      * @createDate 2012-12-12 16:08:54 
  76.      */  
  77.     public void listAll(){  
  78.           
  79.         List<Person> list=pr.findAll();  
  80.         log.debug("查詢結果如下:");  
  81.         for (Person p:list){  
  82.             log.debug(p.toString());  
  83.         }  
  84.           
  85.           
  86.     }  
  87.       
  88.     /** 
  89.      *  
  90.      *<b>function:</b>測試方法 
  91.      * @author cuiran 
  92.      * @createDate 2012-12-12 16:11:37 
  93.      */  
  94.     public void start(){  
  95.         init();  
  96.           
  97.         //insert();  
  98.         //listAll();  
  99.           
  100.         findOne();  
  101.     }  
  102.       
  103.     /** 
  104.      *<b>function:</b>main函數 
  105.      * @author cuiran 
  106.      * @createDate 2012-12-12 11:54:30 
  107.      */  
  108.     public static void main(String[] args) {  
  109.         // TODO Auto-generated method stub  
  110.         MongoTest t=new MongoTest();  
  111.         t.start();  
  112.     }  
  113.   
  114. }  
  115. </span>  


運行出現一下日誌,就沒什麼問題。

[java] view plaincopy
  1. <span style="font-size:18px;color:#3366ff;">2012-12-12 16:23:59:DEBUG com.mongo.test.MongoTest - 開始啓動  
  2. 2012-12-12 16:23:59:INFO org.springframework.context.support.ClassPathXmlApplicationContext - Refreshing org.springframework.context.support.ClassPathXmlApplicationContext@253498: startup date [Wed Dec 12 16:23:59 CST 2012]; root of context hierarchy  
  3. 2012-12-12 16:23:59:INFO org.springframework.beans.factory.xml.XmlBeanDefinitionReader - Loading XML bean definitions from class path resource [applicationContext.xml]  
  4. 2012-12-12 16:24:00:INFO org.springframework.beans.factory.support.DefaultListableBeanFactory - Pre-instantiating singletons in org.springframework.beans.factory.support.DefaultListableBeanFactory@12a0f6c: defining beans [mongo,mongoTemplate,personRepository,org.springframework.context.annotation.internalConfigurationAnnotationProcessor,org.springframework.context.annotation.internalAutowiredAnnotationProcessor,org.springframework.context.annotation.internalRequiredAnnotationProcessor,org.springframework.context.annotation.internalCommonAnnotationProcessor]; root of factory hierarchy  
  5. 2012-12-12 16:24:00:DEBUG com.mongo.test.MongoTest - Person[id=50c83cb552c2ceb0463177d6,name=cuiran,age=27]  
  6. </span>  


 

由於這些程序只是作爲測試使用,對出現的問題, 歡迎留言諮詢。謝謝大家。

 在此附上demo源碼歡迎朋友下載學習  http://vdisk.weibo.com/s/krDlf

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