MongoDB Integration Spring Detail (with code)

Source: Internet
Author: User
Tags findone mongodb stub

Write this article also did the next thinking, first of all, I am poor technology. But just like to study something. Because before this many friends have written similar, a lot of I have read, but the explanation is not deep enough. There is no answer to the questions raised by some friends. Here, I organize it according to my current ability. And finally run successfully.

A problem occurred during the test:

1, Org/springframework/data/mapping/context/mappingcontextaware

2, Src-resolve:cannot resolve the name ' Repository:repository ' to A (n) ' type definition '

All of these are due to a version mismatch. Especially the second one. I see some sort of solution for JPA, but I'm not using JPA here. Later I did not show up to replace the Spring-data-commons package with a version.

Let me start by saying my development environment:

MyEclipse 6.5

MongoDB 2.0.8

Spring 3.0.4

The last is the following 2 (these two versions are not easy to appear in a variety of, assorted problems) Here I'll give the version I'm using.

Spring-data-document

Spring-data-commons

Change all versions must correspond well below is the jar download address
Http://www.springsource.org/spring-data/mongodb
Http://www.springsource.org/spring-data/commons

The download versions are:

Spring-data-commons-dist-1.4.0.m1

Spring-data-document-1.0.0.m2.zip
Here's a picture of my project.

Then start our development tour!

First new application.xml configuration file

<?xml version= "1.0" encoding= "UTF-8"?> <beans xmlns= "Http://www.springframework.org/schema/beans" xml Ns:xsi= "Http://www.w3.org/2001/XMLSchema-instance" xmlns:context= "Http://www.springframework.org/schema/contex T "xmlns:mongo=" Http://www.springframework.org/schema/data/mongo "xsi:schemalocation=" http://www.s   
          Pringframework.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/spri Ng-mongo-1.0.xsd Http://www.springframework.org/schema/beans Http://www.springframework.org/sche Ma/beans/spring-beans-3.0.xsd "> <mongo:mongo host=" 192.168.0.138 "port=" 27017 "/> <bean i D= "Mongotemplate" class= "org.springframework.data.document.mongodb.MongoTemplate" > <constructor-arg ref= "mo NGO "/> <conStructor-arg name= "DatabaseName" value= "db"/> <constructor-arg "name=" defaultcollectionname "person"/   
        > </bean> <bean id= "personrepository" class= "Com.mongo.dao.impl.PersonRepository" > <property name= "Mongotemplate" ref= "mongotemplate" ></property> </bean> <cont 
	 Ext:annotation-config/> </beans>


and then write an interface that operates MongoDB

/** * Abstractrepository.java * Copyright (C) 2012 * Create: 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> Add Object * @author Cuiran * @createDate 2012-12-12 11:41:30/public void inserts (person); /** * *<b>function:</b> find objects by ID * @author Cuiran * @createDate 2012-12-12 11:41:41/Public Pe   
    Rson FindOne (String ID);
    /** * *<b>function:</b> Inquiry ALL * @author Cuiran * @createDate 2012-12-12 16:26:06/   
    
    Public list<person> findall ();
    Public list<person> Findbyregex (String regex);
     /** * *<b>function:</b> Delete the specified ID object * @author cuiran * @createDate 2012-12-12 16:26:16   
    */public void Removeone (String id); /** * *<b>function:</b> Delete all * @author Cuiran * @createDate 2012-12-12 16:25:40/public void RemoveAll ();
     /** * found and modified by ID *<b>function:</b> * @author cuiran * @createDate 2012-12-12 16:25:51   

	
*/public void findandmodify (String id);
 }


to write the implementation class for the corresponding interface:

/** * Personrepository.java * Copyright (C) 2012 * Create: Cuiran 2012-12-12 11:42:51/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 {Priva   

	Te Mongotemplate mongotemplate; /* (non-javadoc) * @see com.mongo.dao.abstractrepository#findall () * * * @Override public list<person> 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 Li St<person> Findbyregex (String regex) {//TODO auto-generated method Stub pattern = Pattern.compile (reg   
	      ex,pattern.case_insensitive);   
	        The 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 fi Ndone (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) {//TODO Auto-generat   
	Ed method Stub Getmongotemplate (). Insert (person);  }/* (non-javadoc) * @see com.mongo.dao.abstractrepository#removeall () * * * @Override public void RemoveAll () {//   
        TODO auto-generated Method Stub list<person> 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.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;
 }

}

The corresponding Person object code is also given here

/** * Person.java * Copyright (C) 2012 * Create: Cuiran 2012-12-12 11:37:16/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 of the age to set */public void Setage (int age) {this.age = age;
		}/** * * @param name * @param age/Public person (String name, int age) {super ();
		THIS.name = name;
	This.age = age;   
	    Public String toString () {return "person[id=" +id+ ", name=" +name+ ", age=" +age+ "]";
 }   


}

Finally write our test class to start testing

/** * Mongotest.java * Copyright (C) 2012 * Create: Cuiran 2012-12-12 11:54:30/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 = Logfactory.getlog (M
	
	OngoTest.class.getName ());
	
	Private Abstractrepository Pr=null;
		 /** * *<b>function:</b> * @author Cuiran * @createDate 2012-12-12 16:08:02/public void init () {
		 Log.debug ("Start");
		  ApplicationContext CTX = new Classpathxmlapplicationcontext ("Applicationcontext.xml");
		 
		
		
	Pr= (personrepository) Ctx.getbean ("Personrepository"); }/** * *<b>function:</b> add
	 * @author Cuiran * @createDate 2012-12-12 16:11:01 */public void Insert () {person p=new person ("Cuiran", 27);
		 Pr.insert (P);
	Log.debug ("add success");  /** * *<b>function:</b> finds objects based on the ID entered * @author cuiran * @createDate 2012-12-12 16:24:10/Public
		void FindOne () {String id= "50c83cb552c2ceb0463177d6";
		Person p= pr.findone (ID);
	Log.debug (P); /** * *<b>function:</b> Query all * @author Cuiran * @createDate 2012-12-12 16:08:54/Public VO
		ID Listall () {list<person> list=pr.findall ();
		Log.debug ("Query results are as follows:");
		for (person p:list) {Log.debug (p.tostring ()); }/** * *<b>function:</b> test method * @author Cuiran * @createDate 2012-12-12 16:11:37 */PU
		
		Blic void Start () {init ();
		Insert ();
		
		Listall ();
	FindOne (); /** *<b>function:</b>main function * @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 ();
 }

}


It's OK to run a log.

2012-12-12 16:23:59:debug com.mongo.test.MongoTest-Start 2012-12-12 16:23:59:info Org.springframework.context.support.classpathxmlapplicationcontext-refreshing Org.springframework.context.support.classpathxmlapplicationcontext@253498:startup Date [Wed Dec 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 Rk.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]


As these procedures are only used as testing, for problems that arise, please leave a message for consultation. Thank you.

In this enclosed demo source welcome Friends Download Learning

Baidu Network disk: Http://pan.baidu.com/s/188Lnr


Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.