在路上

 找回密码
 立即注册
在路上 站点首页 学习 查看内容

MongoDB整合Spring实例详细讲解(含代码)

2017-3-7 12:51| 发布者: zhangjf| 查看: 1101| 评论: 0

摘要: 写这篇文章也做了下思考,首先是本人技术欠佳。但就是喜欢研究一些东西。因为在此之前有很多的朋友已经写过类似的,很多我也看过,但是讲解的不够深入。对有些朋友提出的问题不能给出答案。在这里,我根据我目前的能 ...

写这篇文章也做了下思考,首先是本人技术欠佳。但就是喜欢研究一些东西。因为在此之前有很多的朋友已经写过类似的,很多我也看过,但是讲解的不够深入。对有些朋友提出的问题不能给出答案。在这里,我根据我目前的能力对其进行整理。并最终运行成功。

在测试过程中出现过一下问题:

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配置文件

  1. <?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. <mongo:mongo host="192.168.0.138" port="27017"/>
  13. <bean id="mongoTemplate" class="org.springframework.data.document.mongodb.MongoTemplate">
  14. <constructor-arg ref="mongo"/>
  15. <constructor-arg name="databaseName" value="db"/>
  16. <constructor-arg name="defaultCollectionName" value="person" />
  17. </bean>
  18. <bean id="personRepository" class="com.mongo.dao.impl.PersonRepository">
  19. <property name="mongoTemplate" ref="mongoTemplate"></property>
  20. </bean>
  21. <context:annotation-config />
  22. </beans>
复制代码

然后编写操作mongodb的接口

  1. /**
  2. * AbstractRepository.java
  3. */
  4. package com.mongo.dao;
  5. import java.util.List;
  6. import com.mongo.bean.Person;
  7. /**
  8. * TODO
  9. * @author cuiran
  10. * @version TODO
  11. */
  12. public interface AbstractRepository {
  13. /**
  14. *
  15. *<b>function:</b>添加对象
  16. * @author cuiran
  17. * @createDate 2012-12-12 11:41:30
  18. */
  19. public void insert(Person person);
  20. /**
  21. *
  22. *<b>function:</b>根据ID查找对象
  23. * @author cuiran
  24. * @createDate 2012-12-12 11:41:41
  25. */
  26. public Person findOne(String id);
  27. /**
  28. *
  29. *<b>function:</b>查询所有
  30. * @author cuiran
  31. * @createDate 2012-12-12 16:26:06
  32. */
  33. public List<Person> findAll();
  34. public List<Person> findByRegex(String regex);
  35. /**
  36. *
  37. *<b>function:</b>删除指定的ID对象
  38. * @author cuiran
  39. * @createDate 2012-12-12 16:26:16
  40. */
  41. public void removeOne(String id);
  42. /**
  43. *
  44. *<b>function:</b>删除所有
  45. * @author cuiran
  46. * @createDate 2012-12-12 16:25:40
  47. */
  48. public void removeAll();
  49. /**
  50. * 通过ID找到并修改
  51. *<b>function:</b>
  52. * @author cuiran
  53. * @createDate 2012-12-12 16:25:51
  54. */
  55. public void findAndModify(String id);
  56. }
复制代码

再写对应接口的实现类:

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

这里也给出对应Person对象代码

  1. /**
  2. * Person.java
  3. */
  4. package com.mongo.bean;
  5. import java.io.Serializable;
  6. /**
  7. * TODO
  8. * @author cuiran
  9. * @version TODO
  10. */
  11. public class Person implements Serializable {
  12. /**
  13. *
  14. */
  15. private static final long serialVersionUID = 3617931430808763429L;
  16. private String id;
  17. private String name;
  18. private int age;
  19. public Person() {
  20. super();
  21. }
  22. public Person(String id, String name, int age) {
  23. super();
  24. this.id = id;
  25. this.name = name;
  26. this.age = age;
  27. }
  28. /**
  29. * @return the id
  30. */
  31. public String getId() {
  32. return id;
  33. }
  34. /**
  35. * @param id the id to set
  36. */
  37. public void setId(String id) {
  38. this.id = id;
  39. }
  40. /**
  41. * @return the name
  42. */
  43. public String getName() {
  44. return name;
  45. }
  46. /**
  47. * @param name the name to set
  48. */
  49. public void setName(String name) {
  50. this.name = name;
  51. }
  52. /**
  53. * @return the age
  54. */
  55. public int getAge() {
  56. return age;
  57. }
  58. /**
  59. * @param age the age to set
  60. */
  61. public void setAge(int age) {
  62. this.age = age;
  63. }
  64. /**
  65. *
  66. * @param name
  67. * @param age
  68. */
  69. public Person(String name, int age) {
  70. super();
  71. this.name = name;
  72. this.age = age;
  73. }
  74. public String toString() {
  75. return "Person[id="+id+",name="+name+",age="+age+"]";
  76. }
  77. }
复制代码

最后写出我们的测试类开始进行测试

  1. /**
  2. * MongoTest.java
  3. */
  4. package com.mongo.test;
  5. import java.util.List;
  6. import org.apache.commons.logging.Log;
  7. import org.apache.commons.logging.LogFactory;
  8. import org.springframework.context.ApplicationContext;
  9. import org.springframework.context.support.ClassPathXmlApplicationContext;
  10. import com.mongo.bean.Person;
  11. import com.mongo.dao.AbstractRepository;
  12. import com.mongo.dao.impl.PersonRepository;
  13. /**
  14. * TODO
  15. * @author cuiran
  16. * @version TODO
  17. */
  18. public class MongoTest {
  19. private static Log log = LogFactory.getLog(MongoTest.class.getName());
  20. private AbstractRepository pr=null;
  21. /**
  22. *
  23. *<b>function:</b>
  24. * @author cuiran
  25. * @createDate 2012-12-12 16:08:02
  26. */
  27. public void init(){
  28. log.debug("开始启动");
  29. ApplicationContext ctx = new ClassPathXmlApplicationContext("applicationContext.xml");
  30. pr= (PersonRepository)ctx.getBean("personRepository");
  31. }
  32. /**
  33. *
  34. *<b>function:</b>添加
  35. * @author cuiran
  36. * @createDate 2012-12-12 16:11:01
  37. */
  38. public void insert(){
  39. Person p=new Person("cuiran",27);
  40. pr.insert(p);
  41. log.debug("添加成功");
  42. }
  43. /**
  44. *
  45. *<b>function:</b>根据输入的ID查找对象
  46. * @author cuiran
  47. * @createDate 2012-12-12 16:24:10
  48. */
  49. public void findOne(){
  50. String id="50c83cb552c2ceb0463177d6";
  51. Person p= pr.findOne(id);
  52. log.debug(p);
  53. }
  54. /**
  55. *
  56. *<b>function:</b>查询所有
  57. * @author cuiran
  58. * @createDate 2012-12-12 16:08:54
  59. */
  60. public void listAll(){
  61. List<Person> list=pr.findAll();
  62. log.debug("查询结果如下:");
  63. for (Person p:list){
  64. log.debug(p.toString());
  65. }
  66. }
  67. /**
  68. *
  69. *<b>function:</b>测试方法
  70. * @author cuiran
  71. * @createDate 2012-12-12 16:11:37
  72. */
  73. public void start(){
  74. init();
  75. //insert();
  76. //listAll();
  77. findOne();
  78. }
  79. /**
  80. *<b>function:</b>main函数
  81. * @author cuiran
  82. * @createDate 2012-12-12 11:54:30
  83. */
  84. public static void main(String[] args) {
  85. // TODO Auto-generated method stub
  86. MongoTest t=new MongoTest();
  87. t.start();
  88. }
  89. }
复制代码

运行出现一下日志,就没什么问题。

  1. 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]
复制代码

在此附上demo源码:demo

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持程序员之家。

最新评论

小黑屋|在路上 ( 蜀ICP备15035742号-1 

;

GMT+8, 2025-5-4 02:36

Copyright 2015-2025 djqfx

返回顶部