写这篇文章也做了下思考,首先是本人技术欠佳。但就是喜欢研究一些东西。因为在此之前有很多的朋友已经写过类似的,很多我也看过,但是讲解的不够深入。对有些朋友提出的问题不能给出答案。在这里,我根据我目前的能力对其进行整理。并最终运行成功。
在测试过程中出现过一下问题:
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配置文件
- <span style="font-size:18px;color:#3366ff;"><?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"
- xmlns:mongo="http://www.springframework.org/schema/data/mongo"
- xsi:schemaLocation="http://www.springframework.org/schema/context
- http://www.springframework.org/schema/context/spring-context-3.0.xsd
- http://www.springframework.org/schema/data/mongo
- http://www.springframework.org/schema/data/mongo/spring-mongo-1.0.xsd
- http://www.springframework.org/schema/beans
- http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">
- <mongo:mongo host="192.168.0.138" port="27017"/>
- <bean id="mongoTemplate" class="org.springframework.data.document.mongodb.MongoTemplate">
- <constructor-arg ref="mongo"/>
- <constructor-arg name="databaseName" value="db"/>
- <constructor-arg name="defaultCollectionName" value="person" />
- </bean>
- <bean id="personRepository" class="com.mongo.dao.impl.PersonRepository">
- <property name="mongoTemplate" ref="mongoTemplate"></property>
- </bean>
- <context:annotation-config />
- </beans>
- </span>
然后编写操作mongodb的接口
- <span style="font-size:18px;color:#3366ff;">/**
- * AbstractRepository.java
- * 版权所有(C) 2012
- * 创建:cuiran 2012-12-12 11:40:40
- */
- package com.mongo.dao;
- import java.util.List;
- import com.mongo.bean.Person;
- /**
- * TODO
- * @author cuiran
- * @version TODO
- */
- public interface AbstractRepository {
- /**
- *
- *<b>function:</b>添加对象
- * @author cuiran
- * @createDate 2012-12-12 11:41:30
- */
- public void insert(Person person);
- /**
- *
- *<b>function:</b>根据ID查找对象
- * @author cuiran
- * @createDate 2012-12-12 11:41:41
- */
- public Person findOne(String id);
- /**
- *
- *<b>function:</b>查询所有
- * @author cuiran
- * @createDate 2012-12-12 16:26:06
- */
- public List<Person> findAll();
- public List<Person> findByRegex(String regex);
- /**
- *
- *<b>function:</b>删除指定的ID对象
- * @author cuiran
- * @createDate 2012-12-12 16:26:16
- */
- public void removeOne(String id);
- /**
- *
- *<b>function:</b>删除所有
- * @author cuiran