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

网友投稿 229 2023-06-19


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://springsource.org/spring-data/mongodb

http://springsource.org/spring-dataakwvEeSDiN/commons

下载版本分别为:

spring-data-commons-dist-1.4.0.M1

spring-data-document-1.0.0.M2.zip

下面给出我工程的图片

然后就开始我们开发之旅吧!

首先新建application.xml配置文件

xmlns:xsi="http://w3.org/2001/XMLSchema-instance"

xmlns:context="http://springframework.org/schema/context"

xmlns:mongo="http://springframework.org/schema/data/mongo"

xsi:schemaLocation="http://springframework.org/schema/context

http://springframework.org/schema/context/spring-context-3.0.xsd

http://springframework.org/schema/data/mongo

http://springframework.org/schema/data/mongo/spring-mongo-1.0.xsd

http://springframework.org/schema/beans

http://springframework.org/schema/beans/spring-beans-3.0.xsd">

xmlns:xsi="http://w3.org/2001/XMLSchema-instance"

xmlns:context="http://springframework.org/schema/context"

xmlns:mongo="http://springframework.org/schema/data/mongo"

xsi:schemaLocation="http://springframework.org/schema/context

http://springframework.org/schema/context/spring-context-3.0.xsd

http://springframework.org/schema/data/mongo

http://springframework.org/schema/data/mongo/spring-mongo-1.0.xsd

http://springframework.org/schema/beans

http://springframework.org/schema/beans/spring-beans-3.0.xsd">

然后编写操作mongodb的接口

/**

* AbstractRepository.java

*/

package com.mongo.dao;

import java.util.List;

import com.mongo.bean.Person;

/**

* TODO

* @author cuiran

* @version TODO

*/

public interface AbstractRepository {

/**

*

*function:添加对象

* @author cuiran

* @createDate 2012-12-12 11:41:30

*/

public void insert(Person person);

/**

*

*function:根据ID查找对象

* @author cuiran

* @createDate 2012-12-12 11:41:41

*/

public Person findOne(String id);

/**

*

*function:查询所有

* @author cuiran

* @createDate 2012-12-12 16:26:06

*/

public List findAll();

public List findByRegex(String regex);

/**

*

*function:删除指定的ID对象

* @author cuiran

* @createDate 2012-12-12 16:26:16

*/

public void removeOne(String id);

/**

*

*function:删除所有

* @author cuiran

* @createDate 2012-12-12 16:25:40

*/

public void removeAll();

/**

* 通过ID找到并修改

*function:

* @author cuiran

* @createDate 2012-12-12 16:25:51

*/

public void findAndModify(String id);

}

再写对应接口的实现类:

/**

* PersonRepository.java

*/

package com.mongo.dao.impl;

import java.util.List;

import java.util.regex.Pattern;

import org.springframework.data.document.mongodb.MongoTemplate;

import org.springframework.data.document.mongodb.query.Criteria;

import org.springframework.data.document.mongodb.query.Query;

import org.springframework.data.document.mongodb.query.Update;

import com.mongo.bean.Person;

import com.mongo.dao.AbstractRepository;

/**

* TODO

* @author cuiran

* @version TODO

*/

public class PersonRepository implements AbstractRepository {

private MongoTemplate mongoTemplate;

/* (non-Javadoc)

* @see com.mongo.dao.AbstractRepository#findAll()

*/

@Override

public List findAll() {

// TODO Auto-generated method stub

return getMongoTemplate().find(new Query(), Person.class);

}

/* (non-Javadoc)

* @see com.mongo.dao.AbstractRepository#findAndModify(java.lang.String)

*/

@Override

public void findAndModify(String id) {

// TODO Auto-generated method stub

//new Query(Criteria.where("id").is(id)), new Update().inc("age", 3)

getMongoTemplate().updateFirst(new Query(Criteria.where("id").is(id)), new Update().inc("age", 3));

}

/* (non-Javadoc)

* @see com.mongo.dao.AbstractRepository#findByRegex(java.lang.String)

*/

@Override

public List findByRegex(String regex) {

// TODO Auto-generated method stub

Pattern pattern = Pattern.compile(regex,Pattern.CASE_INSENSITIVE);

Criteria criteria = new Criteria("name").regex(pattern.toString());

return getMongoTemplate().find(new Query(criteria), Person.class);

}

/* (non-Javadoc)

* @see com.mongo.dao.AbstractRepository#findOne(java.lang.String)

*/

@Override

public Person findOne(String id) {

// TODO Auto-generated method stub

return getMongoTemplate().findOne(new Query(Criteria.where("id").is(id)), Person.class);

}

/* (non-Javadoc)

* @see com.mongo.dao.AbstractRepository#insert(com.mongo.bean.Person)

*/

@Override

public void insert(Person person) {

// TODO Auto-generated method stub

getMongoTemplate().insert(person);

}

/* (non-Javadoc)

* @see com.mongo.dao.AbstractRepository#removeAll()

*/

@Override

public void removeAll() {

// TODO Auto-generated method stub

List list = this.findAll();

if(list != null){

for(Person person : list){

getMongoTemplate().remove(person);

}

}

}

/* (non-Javadoc)

* @see com.mongo.dao.AbstractRepository#removeOne(java.lang.String)

*/

@Override

public void removeOne(String id) {

// TODO Auto-generated method stub

Criteria criteria = Criteria.where("id").in(id);

if(criteria == null){

Query query = new Query(criteria);

if(query != null && getMongoTemplate().findOne(query, Person.class) != null)

getMongoTemplate().remove(getMongoTemplate().findOne(query, Person.class));

}

}

/**

* @return the mongoTemplate

*/

public MongoTemplate getMongoTemplate() {

return mongoTemplate;

}

/**

* @param mongoTemplate the mongoTemplate to set

*/

public void setMongoTemplate(MongoTemplate mongoTemplate) {

this.mongoTemplate = mongoTemplate;

}

}

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

/**

* Person.java

*/

package com.mongo.bean;

import java.io.Serializable;

/**

* TODO

* @author cuiran

* @version TODO

*/

public class Person implements Serializable {

/**

*

*/

private static final long serialVersionUID = 3617931430808763429L;

private String id;

private String name;

private int age;

public Person() {

super();

}

public Person(String id, String name, int age) {

super();

this.id = id;

this.name = name;

this.age = age;

}

/**

* @return the id

*/

public String getId() {

return id;

}

/**

* @param id the id to set

*/

public void setId(String id) {

this.id = id;

}

/**

* @return the name

*/

public String getName() {

return name;

}

/**

* @param name the name to set

*/

public void setName(String name) {

this.name = name;

}

/**

* @return the age

*/

public int getAge() {

return age;

}

/**

* @param age the age to set

*/

public void setAge(int age) {

this.age = age;

}

/**

*

* @param name

* @param age

*/

public Person(String name, int age) {

super();

http:// this.name = name;

this.age = age;

}

public String toString() {

return "Person[id="+id+",name="+name+",age="+age+"]";

}

}

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

/**

* MongoTest.java

*/

package com.mongo.test;

import java.util.List;

import org.apache.commons.logging.Log;

import org.apache.commons.logging.LogFactory;

import org.springframework.context.ApplicationContext;

import org.springframework.context.support.ClassPathXmlApplicationContext;

import com.mongo.bean.Person;

import com.mongo.dao.AbstractRepository;

import com.mongo.dao.impl.PersonRepository;

/**

* TODO

* @author cuiran

* @version TODO

*/

public class MongoTest {

private static Log log = LogFactory.getLog(MongoTest.class.getName());

private AbstractRepository pr=null;

/**

*

*function:

* @author cuiran

* @createDate 2012-12-12 16:08:02

*/

public void init(){

log.debug("开始启动");

ApplicationContext ctx = new ClassPathXmlApplicationContext("applicationContext.xml");

pr= (PersonRepository)ctx.getBean("personRepository");

}

/**

*

*function:添加

* @author cuiran

* @createDate 2012-12-12 16:11:01

*/

public void insert(){

Person p=new Person("cuiran",27);

pr.insert(p);

log.debug("添加成功");

}

/**

*

*function:根据输入的ID查找对象

* @author cuiran

* @createDate 2012-12-12 16:24:10

*/

public void findOne(){

String id="50c83cb552c2ceb0463177d6";

Person p= pr.findOne(id);

log.debug(p);

}

/**

*

*function:查询所有

* @author cuiran

* @createDate 2012-12-12 16:08:54

*/

public void listAll(){

List list=pr.findAll();

log.debug("查询结果如下:");

for (Person p:list){

log.debug(p.toString());

}

}

/**

*

*function:测试方法

* @author cuiran

* @createDate 2012-12-12 16:11:37

*/

public void start(){

init();

//insert();

//listAll();

findOne();

}

/**

*function:main函数

* @author cuiran

* @createDate 2012-12-12 11:54:30

*/

public static void main(String[] args) {

// TODO Auto-generated method stub

MongoTest t=new MongoTest();

t.start();

}

}

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

2012-12-12 16:23:59:DEBUG com.mongo.test.MongoTest - 开始启动

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

2012-12-12 16:23:59:INFO org.springframework.beans.factory.xml.XmlBeanDefinitionReader - Loading XML bean definitions from class path resource [applicationContext.xml]

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

2012-12-12 16:24:00:DEBUG com.mongo.test.MongoTest - Person[id=50c83cb552c2ceb0463177d6,name=cuiran,age=27]

在此附上demo源码:demo


版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。

上一篇:微信小程序 数据封装,参数传值等经验分享
下一篇:div实现自适应高度的textarea实现angular双向绑定
相关文章

 发表评论

暂时没有评论,来抢沙发吧~