Connect and operate mongodb3.0 with spring

Source: Internet
Author: User

There's a record in front of it. Connect and manipulate the MongoDB database directly in Java code without using spring, followed by a record of using spring as a simple way to manipulate MongoDB in Java.
Maven Guide Package configuration:Because Sping and SPRINGMVC are involved, it is also necessary to import their related packages:
<project xmlns= "http://maven.apache.org/POM/4.0.0" xmlns:xsi= "Http://www.w3.org/2001/XMLSchema-instance" xsi: schemalocation= "http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd" > <modelversion >4.0.0</modelVersion> <groupId>spring_mongo</groupId> <artifactid>spring_mongo</ artifactid> <packaging>war</packaging> <version>0.0.1-SNAPSHOT</version> <name> Spring_mongo Maven webapp</name> <url>http://maven.apache.org</url> <dependencies> < Dependency> <groupId>org.springframework.data</groupId> <artifactid>spring-data-mongodb        </artifactId> <version>1.8.0.RELEASE</version> </dependency> <dependency> <groupId>org.mongodb</groupId> <artifactId>mongo-java-driver</artifactId> <vers Ion>3.0.3</version> </dependency> <dependEncy> <groupId>commons-logging</groupId> <artifactId>commons-logging</artifactId> <version>1.2</version> </dependency> <dependency> &LT;GROUPID&GT;ORG.SPRINGFR Amework</groupid> <artifactId>spring-test</artifactId> <version>4.1.6.release</ve rsion> </dependency> <dependency> <groupId>junit</groupId> &LT;ARTIFACTID&G        t;junit</artifactid> <version>4.11</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context</artifactId> <v ersion>4.1.7.release</version> </dependency> <dependency> <groupid>org.springframe Work</groupid> <artifactId>spring-context-support</artifactId> <version>4.0.9.releas E</version> </dependency> </dependencies> <build> <plugins> <plugin> <artif Actid>maven-compiler-plugin</artifactid> <version>2.3.2</version> <c                    Onfiguration> <source>1.7</source> <target>1.7</target>                        <encoding>UTF-8</encoding> <compilerArguments> <verbose/> <bootclasspath>${java.home}/lib/rt.jar;${java.home}/lib/jce.jar</boot classpath> </compilerArguments> </configuration> </plug in> </plugins> <finalName>spring_mongo</finalName> </build></project>



Spring Base configuration:The main is to open the annotation scan, etc.:
<?xml version= "1.0" encoding= "UTF-8"? ><beans xmlns:task= "Http://www.springframework.org/schema/task" xmlns= "Http://www.springframework.org/schema/beans" xmlns:xsi= "Http://www.w3.org/2001/XMLSchema-instance" xmlns: context= "Http://www.springframework.org/schema/context" xsi:schemalocation= "http://www.springframework.org/ schema/beanshttp://www.springframework.org/schema/beans/spring-beans-3.0.xsdhttp://www.springframework.org/ schema/contexthttp://www.springframework.org/schema/context/spring-context-3.0.xsdhttp:// Www.springframework.org/schema/taskhttp://www.springframework.org/schema/task/spring-task-3.1.xsd "> <!-- Auto-scan (auto-inject)-<context:component-scan base-package= "spring_mogo.dao.daoImp"/> <!--importing MongoDB configuration Files--&G    T <import resource= "Spring-mongodb305.xml"/> <!--opening annotations--<context:annotation-config/></beans& Gt


spring connect MongoDB and establish the configuration of the associated factory:
<?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:p= "http://www.springframework.org/schema/p" xmlns:mongo= " Http://www.springframework.org/schema/data/mongo "xsi:schemalocation=" http://www.springframework.org/schema/ Beans Http://www.springframework.org/schema/beans/spring-beans-3.0.xsd Http://www.springframe Work.org/schema/data/mongo http://www.springframework.org/schema/data/mongo/spring-mongo.xsd "> <!--SP Ring Connection MongoDB Database configuration--<mongo:mongo-client host= "192.168.0.201" port= "27017" credentials= "tuzongxun:[email& Nbsp;protected] "id=" MONGO "> <mongo:client-options write-concern=" SAFE "/> </mongo:mongo-client&gt     ;    <mongo:db-factory id= "Mongodbfactory" dbname= "mongotest" mongo-ref= "Mongo"/> <!--just use this call to the appropriate method-- <bean id= "Mongotemplate" class= "ORG.SPRINGFRAmework.data.mongodb.core.MongoTemplate "> <constructor-arg name=" mongodbfactory "ref=" Mongodbfactory "/> </bean> </beans>


entity classes corresponding to the database:It is important to note that there is a need to implement the serialized interface and set the UID properties, otherwise the database return result can not be converted to object properties directly in the operation:
Package Spring_mongo.models;import Java.io.serializable;public class Usermodel implements Serializable {    private Static final Long serialversionuid = 1L;    Private String userName;    private String password;    Public Usermodel (String userName, string password) {        super ();        This.username = UserName;        This.password = password;    }    Public String GetUserName () {        return userName;    }    public void Setusername (String userName) {        this.username = userName;    }    Public String GetPassword () {        return password;    }    public void SetPassword (String password) {        this.password = password;    }}


Get operations based on spring configuration MongoDB applicationcontextaware Interface:
Package Spring_mogo.dao.daoimp;import Org.springframework.beans.beansexception;import Org.springframework.context.applicationcontext;import Org.springframework.context.ApplicationContextAware; Import Org.springframework.data.mongodb.core.mongotemplate;public abstract class Abstractbasemongotemplete Implements        Applicationcontextaware {    protected mongotemplate mongotemplate;    /**     * @Description based on profile settings mongotemplate     * @param mongotemplate     *    /public void Setmongotemplate ( Mongotemplate mongotemplate) {        this.mongotemplate = mongotemplate;    }    @Override public    void Setapplicationcontext (ApplicationContext applicationcontext)            throws Beansexception {        Mongotemplate mongotemplate = Applicationcontext.getbean (                "Mongotemplate", mongotemplate.class);        Setmongotemplate (mongotemplate);    }}



The interface of the operational database and the corresponding implementation class:Demonstrates the most basic additions and deletions, which need to be noted in the Declaration of parameters and the conversion of the entity class when the return data is received: (1) interface:
Package Spring_mogo.dao;import Java.util.list;import Spring_mongo.models.usermodel;public interface UserDao {/** * Query data * * @author: Tuzongxun * @Title: FINDALL * @param @return * @return list<usermodel> *    @date May 3:07:39 PM * @throws */public list<usermodel> findAll (); /** * Added Data * * @author: Tuzongxun * @Title: Insertuser * @param @param user * @return void * @    Date May: 3:09:45 PM * @throws */public void Insertuser (Usermodel user);     /** * Delete Data * * @author: Tuzongxun * @Title: Removeuser * @param @param userName * @return void    * @date May 3:09:55 PM * @throws */public void Removeuser (String userName); /** * Modify Data * * @author: Tuzongxun * @Title: UpdateUser * @param @param user * @return void * @    Date May: 3:10:06 PM * @throws */public void UpdateUser (Usermodel user);/** * Search by condition * * @author: Tuzongxun * @Title: Findforrequery * @param * @return void * @date Ma Y, 3:23:37 PM * @throws * * Public list<usermodel> findforrequery (String userName);


(2) Implementation class, here to inheritAbstractbasemongotemplete class to obtain mongotemplete for various operations:
Package Spring_mogo.dao.daoimp;import Java.util.list;import Org.springframework.data.mongodb.core.query.Criteria; Import Org.springframework.data.mongodb.core.query.query;import Org.springframework.data.mongodb.core.query.update;import Org.springframework.stereotype.component;import Spring _mogo.dao.userdao;import Spring_mongo.models.usermodel;import Com.mongodb.basicdbobject;import Com.mongodb.DBObject, @Component ("Userdaoimp") public class Userdaoimp extends Abstractbasemongotemplete implements Userdao {/** * query all data * * @author: Tuzongxun * @Title: FindAll * @Description: TODO * @param @        return * @date May 3:10:29 PM * @throws */@Override public list<usermodel> findAll () {                The collection corresponding to the Corpse class and the corresponding set name, so that the query results directly mapped list<usermodel> userlist = Mongotemplate.findall (Usermodel.class,        "User");    return userlist; }/** * Added data * * @author: Tuzongxun * @Title: Insertuser * @DescrIption:todo * @param @param user * @date May 3:10:45 PM * @throws */@Override public void        Insertuser (Usermodel user) {//sets the document object that needs to be inserted into the database DBObject objects = new Basicdbobject ();        Object.put ("UserName", User.getusername ());        Object.put ("Password", User.getpassword ());    Mongotemplate.insert (object, "user"); /** * Delete Data conditionally * * @author: Tuzongxun * @Title: Removeuser * @Description: TODO * @param @para M UserName * @date May 3:11:01 PM * @throws */@Override public void Removeuser (String userName        {//Set the delete condition, if the condition content is empty, delete all query query = new query ();        criteria = new Criteria ("UserName");        Criteria.is (UserName);        Query.addcriteria (criteria);    Mongotemplate.remove (query, "user"); }/** * Modify Data * * @author: Tuzongxun * @Title: UpdateUser * @Description: TODO * @param @param u Ser * @date May 13, 2016 3:11:12 PM * @throws */@Override public void UpdateUser (Usermodel user) {//Set Modify condition Query        query = new query ();        criteria = new Criteria ("UserName");        Criteria.is (User.getusername ());        Query.addcriteria (criteria);        Set Modify Update update = update.update ("Password", User.getpassword ());    Parameters: Query condition, change result, set name Mongotemplate.updatefirst (query, update, "user"); /** * Search by condition * * @author: Tuzongxun * @Title: Findforrequery * @Description: TODO * @param @p Aram UserName * @date May, 4:08:15 PM * @throws */@Override public list<usermodel> FINDFO        Rrequery (String userName) {query query = new query ();        criteria = new Criteria ("UserName");        Criteria.is (UserName);        Query.addcriteria (criteria); Query condition, collection corresponding entity class, collection name list<usermodel> userlist = mongotemplate.find (query, Usermodel.class, "uSer ");    return userlist; }}

Test class:To verify the correctness of the above code and configuration, the test class code is as follows:
Package Spring_mongo.test;import Java.util.list;import Org.junit.test;import org.junit.runner.runwith;import Org.springframework.beans.factory.annotation.autowired;import Org.springframework.test.context.contextconfiguration;import Org.springframework.test.context.junit4.springjunit4classrunner;import Spring_mogo.dao.userdao;import Spring_ Mongo.models.UserModel; @RunWith (Springjunit4classrunner.class) @ContextConfiguration (locations = {"Classpath:    Spring.xml "}) public class Mongotest {@Autowired private Userdao Userdao; /** * Query Test * * @author: Tuzongxun * @Title: Monfindtest * @param * @return void * @date May 13 , 3:27:51 PM * @throws */@Test public void Monfindtest () {List<usermodel> usermodels = u        Serdao.findall ();                if (usermodels! = null && usermodels.size () > 0) {for (Usermodel user:usermodels) { System.out.println (User.getusername () + ":" + user. GetPassword ()); }}}/** * Insert data Test * * @author: Tuzongxun * @Title: Moninserttest * @param * @return void * @date May 3:27:38 PM * @throws */@Test public void Moninserttest () {Usermodel u        Ser = new Usermodel ("test111", "123456");        Userdao.insertuser (user);    This.monfindtest ();  /** * Delete Test * * @author: Tuzongxun * @Title: Monremovetest * @param * @return void * @date 3:28:06 PM * @throws * * * @Test public void Monremovetest () {String userName = "test111"        ;        Userdao.removeuser (UserName);    This.monfindtest ();  /** * Test Modification * * @author: Tuzongxun * @Title: Monupdatetest * @param * @return void * @date 3:50:08 PM * @throws * * @Test public void Monupdatetest () {Usermodel user = new Usermo        Del ("test111", "Test");        Userdao.updateuser (user); ThIs.monfindtest (); /** * Search by condition * * @author: Tuzongxun * @Title: Monfindforruq * @param * @return void * @dat E May 4:10:53 PM * @throws */@Test public void Monfindforruq () {String userName = "test111        ";        list<usermodel> usermodels = Userdao.findforrequery (userName);                if (usermodels! = null && usermodels.size () > 0) {for (Usermodel user:usermodels) {            System.out.println (User.getusername () + ":" + User.getpassword ()); }        }    }}


Connect and operate mongodb3.0 with spring

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.