System environment:
Operating system: Windows XP
Database: mongodb2.0.6
Driver Package: Spring3.1.2 + mongodb2.7.3 + spring-data-mongodb1.0.1
Description: For XP system users, when performing Mongod.exe installation MongoDB, unable to locate the program input point InterlockedCompareExchange64 on the dynamic link library KERNEL32.dll, This is because XP is no longer supported by the newest development branch. That is, your MongoDB installation package does not support XP. V2.0.6 is the latest and last new version to support XP. So the author uses the database for 2.0.6
Project structure:
Configuration Description:
The Web.xml file configuration spring is related to SPRINGMVC.
<?xml version= "1.0" encoding= "UTF-8"?>
<web-app version= "2.5"
Xmlns= "Http://java.sun.com/xml/ns/javaee"
Xmlns:xsi= "Http://www.w3.org/2001/XMLSchema-instance"
Xsi:schemalocation= "Http://java.sun.com/xml/ns/javaee
Http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd ">
<!--spring configuration-->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/context/spring-context.xml</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<!--spring MVC configuration-->
<servlet>
<servlet-name>springmvc</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/context/servlet-context.xml</param-value> <!--Specify the location of the XML file-->
</init-param>
<load-on-startup>4</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>springmvc</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
</web-app>
SPRINGMVC configuration file Servlet-context.xml
<?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:util= "Http://www.springframework.org/schema/util"
xmlns:p= "http://www.springframework.org/schema/p"
xmlns:aop= "HTTP://WWW.SPRINGFRAMEWORK.ORG/SCHEMA/AOP"
xmlns:tx= "Http://www.springframework.org/schema/tx"
Xmlns:mvc= "Http://www.springframework.org/schema/mvc"
xmlns:context= "Http://www.springframework.org/schema/context"
Xsi:schemalocation= "
Http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.1.xsd
Http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-3.1.xsd
Http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.1.xsd
HTTP://WWW.SPRINGFRAMEWORK.ORG/SCHEMA/AOP http://www.springframework.org/schema/aop/spring-aop-3.1.xsd
Http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.1.xsd
Http://www.springframework.org/schema/context
Http://www.springframework.org/schema/context/spring-context-3.1.xsd ">
<!--dispatcherservlet Context:defines this servlet ' s request-processing infrastructure-->
<!--enables the Spring MVC @Controller programming Model-->
<mvc:annotation-driven/>
<context:component-scan base-package= "Com.pudp"/>
<!--configuration is based on session processing, the submitted locale parameters are processed-->
<bean id= "Localeresolver" class= "Org.springframework.web.servlet.i18n.SessionLocaleResolver" >
<!--This property can not be configured-->
<property name= "Defaultlocale" value= "ja" ></property>
</bean>
<!--resolves views selected for rendering by @Controllers to. JSP resources in The/web-inf/views directory-->
<bean class= "Org.springframework.web.servlet.view.InternalResourceViewResolver" >
<property name= "prefix" value= "/web-inf/views/"/>
<property name= "suffix" value= ". jsp"/>
</bean>
</beans>
Spring configuration file Spring-context.xml
<?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:util= "Http://www.springframework.org/schema/util"
xmlns:p= "http://www.springframework.org/schema/p"
xmlns:aop= "HTTP://WWW.SPRINGFRAMEWORK.ORG/SCHEMA/AOP"
xmlns:tx= "Http://www.springframework.org/schema/tx"
xmlns:context= "Http://www.springframework.org/schema/context"
Xsi:schemalocation= "
Http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.1.xsd
Http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-3.1.xsd
Http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.1.xsd
HTTP://WWW.SPRINGFRAMEWORK.ORG/SCHEMA/AOP http://www.springframework.org/schema/aop/spring-aop-3.1.xsd
Http://www.springframework.org/schema/context
Http://www.springframework.org/schema/context/spring-context-3.1.xsd ">
<context:annotation-config/>
<context:component-scan base-package= "Com.pudp"/>
<!--Import the MongoDB profile-->
<import resource= "Mongodb-context.xml"/>
</beans>
MongoDB configuration file Mongodb-context.xml
<?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 ">
<!--Load MongoDB property profile-->
<context:property-placeholder location= "Classpath:mongodb.properties"/>
<!--define the MONGO object, which corresponds to the mongo,replica-set of the MongoDB official jar package to set the IP address and port of the cluster replica-->
<mongo:mongo id= "MONGO" replica-set= "${mongo.hostport}" >
<!--settings for some connection properties-->
<mongo:options
Connections-per-host= "${mongo.connectionsperhost}"
Threads-allowed-to-block-for-connection-multiplier= "${mongo.threadsallowedtoblockforconnectionmultiplier}"
connect-timeout= "${mongo.connecttimeout}"
Max-wait-time= "${mongo.maxwaittime}"
auto-connect-retry= "${mongo.autoconnectretry}"
Socket-keep-alive= "${mongo.socketkeepalive}"
socket-timeout= "${mongo.sockettimeout}"
slave-ok= "${mongo.slaveok}"
Write-number= "1"
write-timeout= "0"
Write-fsync= "true"/>
</mongo:mongo>
<mongo:db-factory dbname= "Database" mongo-ref= "MONGO"/>
<bean id= "Mongotemplate" class= "Org.springframework.data.mongodb.core.MongoTemplate" >
<constructor-arg ref= "Mongo"/>
<constructor-arg name= "DatabaseName" value= "Db_mongo"/>
</bean>
</beans>
MongoDB Property configuration File Mongodb.properties
mongo.hostport=127.0.0.1:27017
Mongo.connectionsperhost=8
Mongo.threadsallowedtoblockforconnectionmultiplier=4
#连接超时时间
mongo.connecttimeout=1000
#等待时间
mongo.maxwaittime=1500
Mongo.autoconnectretry=true
Mongo.socketkeepalive=true
#Socket超时时间
mongo.sockettimeout=1500
Mongo.slaveok=true
Write controller, Service, DAO related. Here we test the implementation mechanism for collection in the following Spring-data-mong. We create different entity types Member, Article
Then write the corresponding service, DAO implementation. Here we focus on persistence layer implementation
Operation implementation of persistence layer
Articledao
Package Com.pudp.dao;
Import Org.springframework.stereotype.Repository;
Import Com.pudp.base.MongoGenDao;
Import com.pudp.model.Article;
/**
* Description:
*
* @author <a href= ' mailto:dennisit@163.com ' > Cn. If year (en.dennisit) </a> Copy right since 2013-10-16
*
* Com.pudp.dao.ArticleDao.java
*
*/
@Repository
public class Articledao extends mongogendao<article>{
/**
* Implement Hook method, return the type of reflection
* @author <a href= ' mailto:dennisit@163.com ' >cn Sujonin (en.dennisit) </a> Copy right since 2013-10-13
*
* @return
*/
@Override
Protected class<article> Getentityclass () {
return article.class;
}
}
Memberdao
Package Com.pudp.dao;
Import Org.springframework.stereotype.Repository;
Import Com.pudp.base.MongoGenDao;
Import Com.pudp.model.Member;
/**
* Description:
*
* @author <a href= ' mailto:dennisit@163.com ' > Cn. Sujonin (en.dennisit) </a> Copy right since 2013-10-13
*
* Com.pudp.dao.MemberDao.java
*
*/
@Repository
public class Memberdao extends mongogendao<member>{
/**
* Implement Hook method, return the type of reflection
* @author <a href= ' mailto:dennisit@163.com ' >cn Sujonin (en.dennisit) </a> Copy right since 2013-10-13
*
* @return
*/
@Override
Protected class<member> Getentityclass () {
return member.class;
}
}
In Mongogendao, we implemented adding data to the library
Package com.pudp.base;
Import org.springframework.beans.factory.annotation.Autowired;
Import Org.springframework.data.mongodb.core.MongoTemplate;
/**
* Description:
*
* @author <a href= ' mailto:dennisit@163.com ' > Cn. Sujonin (en.dennisit) </a> Copy right since 2013-10-13
*
* Com.pudp.base.MongoGenDao.java
*
*/
Public abstract class Mongogendao<t> {
@Autowired
protected Mongotemplate mongotemplate;
/**
* Save an object
*
* @author <a href= ' mailto:dennisit@163.com ' >cn Sujonin (en.dennisit) </a> Copy right since 2013-10-13 03:37:28
*
* @param t
* @return
*/
public void Save (t) {
This.mongoTemplate.save (t);
}
/**
* Automatically inject bean service for attributes
*
* @author <a href= ' mailto:dennisit@163.com ' >cn.pudp (en.dennisit) </a> Copy Right since 2013-10-13 afternoon 03 : 21:23
*
* @param mongotemplate
*/
public void Setmongotemplate (Mongotemplate mongotemplate) {
This.mongotemplate = mongotemplate;
}
}
What needs to be explained here is the Mongotemplate management of the library.
The management of Mongotemplate to library collection
We use the mongotemplate to manipulate the persistence layer. If we don't specify CollectionName here, the class name of the entity type is the collection names in the library, and after we perform the data warehousing operation, we look up the following information from the database.
Of course, if we want to define the collection name of the database ourselves, we can specify it in the Persistence layer DAO.
SPRINGMVC consolidation MONGODB Development of advanced Operations springmvc+ MONGODB CRUD + Paging implementation
Development environment:
Operating system: Windows XP
mongodb:2.0.6
Dependent Package: Spring3.2.2 + spring-data-mongodb-1.3.0 + spring-data-1.5 + mongodb2.7.3
Description: SPRINGMVC integration MongoDB recommended to select a stable version of the spring-data-mongdb. There are data mapping bugs in Mongodb1.0.1. So use 1.3.0.
Project Structure Chart:
Description
Persistence layer Operations Use the Mongotemplate class operation. Enables you to interoperate objects with data in the MongoDB library.
What needs to be explained here is that the id attribute in my Entity object corresponds to the _id attribute in the record in the library.
MongoDB and SPRINGMVC consolidation See documentation: Http://www.linuxidc.com/Linux/2015-02/114229.htm
Advanced Operations for MongoDB:
Adding objects to a database
/**
* Save an object
*
* @author <a href= ' mailto:dennisit@163.com ' >cn Sujonin (en.dennisit) </a> Copy right since 2013-10-13 03:37:28
*
* @param t
* @return
*/
public void Save (t) {
Log.info ("[Mongo Dao]save:" + t);
This.mongoTemplate.save (t);
}
Querying objects from libraries based on IDs
/**
* Query objects from collection based on ID
*
* @author <a href= ' mailto:dennisit@163.com ' >cn Sujonin (en.dennisit) </a> Copy right since 2013-10-17 01:59:55
*
* @param ID
* ID of the entity object corresponding to the _id field recorded in collection.
* <p>
* What needs to be explained is that the Mongdo itself does not have a primary key self-enhancement mechanism. Solution
* <ol>
* <li> entity in the warehouse, the program for the entity to assign the primary key value.
* <li> entity Warehousing, the custom function in MongoDB to implement the primary key self-increasing mechanism. Define methods similar to JS code
* </ol>
* </p>
* @return
*/
Public T Querybyid (String ID) {
Query query = new query ();
Criteria criteria = Criteria.where ("_id"). is (ID);
Query.addcriteria (criteria);
Log.info ("[Mongo Dao]querybyid:" + query);
return This.mongoTemplate.findOne (query, This.getentityclass ());
}
Query from the library based on criteria
/**
* Query collection based on criteria
*
* @author <a href= ' mailto:dennisit@163.com ' >cn Sujonin (en.dennisit) </a> Copy right since 2013-10-13 03:32:54
*
* @param query
* Query conditions
* @return
* Meet the criteria of the set
*/
Public list<t> querylist (query query) {
Log.info ("[Mongo Dao]querylist:" + query);
return this.mongoTemplate.find (query, This.getentityclass ());
}
Query individual records based on criteria
/**
* Query individual entities by criteria
*
* @author <a href= ' mailto:dennisit@163.com ' >cn Sujonin (en.dennisit) </a> Copy right since 2013-10-13 03:33:12
*
* @param query
* @return
*/
Public T queryone (query query) {
Log.info ("[Mongo Dao]queryone:" + query);
return This.mongoTemplate.findOne (query, This.getentityclass ());
}
Note: Query single use is Mongotemplate.findone method, query a lot of use is mongotemplate.find.
Paging Query Operations
/**
* Paging through the condition of the query
*
* @author <a href= ' mailto:dennisit@163.com ' >cn Sujonin (en.dennisit) </a> Copy right since 2013-10-13 03:33:30
*
* @param query
* Query conditions
* @param start
* Query Start value
* <strong> similar to limit start in MySQL query, start</strong> in size
* @param size
* Query Size
* <strong> similar to limit start in MySQL query, size</strong> in size
* @return
* Meet the criteria of the set
*/
Public list<t> getpage (query query, int start, int size) {
Query.skip (start);
Query.limit (size);
Log.info ("[Mongo Dao]querypage: + query +" ("+ Start +", "+ Size +"));
list<t> lists = this.mongoTemplate.find (query, This.getentityclass ());
return lists;
}
/**
* Query for paging service according to the total number of records in the library
*
* @author <a href= ' mailto:dennisit@163.com ' >cn Sujonin (en.dennisit) </a> Copy right since 2013-10-13 03:35:44
*
* @param query
* Query conditions
* @return
* Total number of records that meet the criteria
*/
Public Long getpagecount (query query) {
Log.info ("[Mongo Dao]querypagecount:" + query);
return This.mongoTemplate.count (query, This.getentityclass ());
}
Delete action based on ID
/**
* Delete user based on ID
*
* @author <a href= ' mailto:dennisit@163.com ' >cn Sujonin (en.dennisit) </a> Copy right since 2013-10-13 04:09:20
*
* @param ID
*/
public void Deletebyid (String id) {
Criteria criteria = Criteria.where ("_id"). In (ID);
if (Null!=criteria) {
Query query = new query (criteria);
Log.info ("[Mongo Dao]deletebyid:" + query);
if (null!=query && this.queryone (query)!=null) {
This.delete (query);
}
}
}
Delete Object action
/**
* Delete Object
*
* @author <a href= ' mailto:dennisit@163.com ' >cn Sujonin (en.dennisit) </a> Copy right since 2013-10-13 03:45:33
*
* @param t
*/
public void Delete (T t) {
Log.info ("[Mongo Dao]delete:" + t);
This.mongoTemplate.remove (t);
}
To modify an operation:
Description: MongoDB's modification operation is roughly 3.
Mongotemplate.updatefirst operation, Mongotemplate.updatemulti operation, This.mongoTemplate.upsert operation.
Each represents the modification of the first article, the modification of all eligible conditions, and the addition if they are not present at the time of modification.
Modify the first record that satisfies a condition
/**
* Update the first record that meets the criteria
*
* @author <a href= ' mailto:dennisit@163.com ' >cn Sujonin (en.dennisit) </a> Copy right since 2013-10-13 03:47:10
*
* @param query
* @param update
*/
public void Updatefirst (Query query,update Update) {
Log.info ("[Mongo Dao]updatefirst:query (" + Query + "), update (" + update + "));
This.mongoTemplate.updateFirst (query, update, This.getentityclass ());
}
Modify multiple records that meet a condition
/**
* Update all records that meet the criteria
*
* @author <a href= ' mailto:dennisit@163.com ' >cn Sujonin (en.dennisit) </a> Copy right since 2013-10-13 03:48:02
*
* @param query
* @param update
*/
public void Updatemulti (query query, update update) {
Log.info ("[Mongo Dao]updatemulti:query (" + Query + "), update (" + update + "));
This.mongoTemplate.updateMulti (query, update, This.getentityclass ());
}
Modify, add if the object you want to modify does not exist
/**
* Find updates, and if no records are found, insert the updated records into the library
*
* @author <a href= ' mailto:dennisit@163.com ' >cn Sujonin (en.dennisit) </a> Copy right since 2013-10-13 03:48:58
*
* @param query
* @param update
*/
public void Updateinser (query query, update update) {
Log.info ("[Mongo Dao]updateinser:query (" + Query + "), update (" + update + "));
This.mongoTemplate.upsert (query, update, This.getentityclass ());
}
The above operation is MongoDB's underlying operation encapsulation, which uses the abstract class of the generic implementation Mongogendao.java, defines the hook method in the generic, and then the DAO class inherits the abstract class, implements the Hook method, and returns the type of reflection. The hook method is defined as follows:
/**
* Hook method, subclass implementation returns the type of reflection object
*
* @author <a href= ' mailto:dennisit@163.com ' >cn.pudp (en.dennisit) </a> Copy Right since 2013-10-13 afternoon 03 : 21:48
*
* @return
*/
Protected abstract class<t> getentityclass ();
MongoDB Basic operation encapsulation is about that much.
The next step is to make a copy of our persistence layer base operation in the data DAO as needed. The example is the base implementation of the member management.
Package Com.pudp.dao;
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.Repository;
Import Com.pudp.base.MongoGenDao;
Import Com.pudp.model.Member;
Import Com.pudp.util.StringUtil;
/**
* Description:
*
* @author <a href= ' mailto:dennisit@163.com ' > Cn. Sujonin (en.dennisit) </a> Copy right since 2013-10-13
*
* Com.pudp.dao.MemberDao.java
*
*/
@Repository
public class Memberdao extends mongogendao<member>{
/**
* Paging query corresponds to the Db.member.find () in MongoDB operation (). Skip (10); limit.
*
* @author <a href= ' mailto:dennisit@163.com ' >cn Sujonin (en.dennisit) </a> Copy right since 2013-10-13 04:09:58
*
* @param member
* Condition of the query
* @param start
* The starting value of the user paging query
* @param size
* Number of data queried
*
* @return
* Returns the query to the data collection
*/
Public list<member> querypage (member, integer start, integer size) {
Query query = new query ();
Here you can increase the criteria for paging query criteria. Then Query.addcriteria (criteria);
return this.getpage (query, (start-1) *size,size);
}
/**
* The total number of records that the query satisfies the paging
*
* @author <a href= ' mailto:dennisit@163.com ' >cn Sujonin (en.dennisit) </a> Copy right since 2013-10-16 10:20:12
*
* @param member
* Condition of the query
* @return
* Returns the total number of records that meet the criteria
*/
Public Long Querypagecount {
Query query = new query ();
Here you can increase the criteria for paging query criteria. Then Query.addcriteria (criteria);
return This.getpagecount (query);
}
/**
* Update operation
*
* @author <a href= ' mailto:dennisit@163.com ' >cn Sujonin (en.dennisit) </a> Copy right since 2013-10-17 02:21:26
*
* @param member
* The data to be updated
* @throws Exception
* Update exception
*/
public void Updatefirst (member member) throws Exception {
Update update = new update ();
if (Null==member.getid () | | "". Equals (Member.getid (). Trim ())) {
If the primary key is empty, no modification is made
throw new Exception ("Update data Id is Null");
}
if (Stringutil.isnotnullvalue (Member.getusername ())) {
Update.set ("username", member.getusername ());
}
if (Stringutil.isnotnullvalue (Member.getpassword ())) {
Update.set ("Password", Member.getpassword ());
}
if (Stringutil.isnotnullvalue (Member.getsex ())) {
Update.set ("Sex", member.getsex ());
}
if (Stringutil.isnotnullvalue (Member.getemail ())) {
Update.set ("Email", member.getemail ());
}
This.updatefirst (Query.query (Criteria.where ("_id"). Is (Member.getid ()), update);
}
/**
* Update all data in the library
*
* @author <a href= ' mailto:dennisit@163.com ' >cn Sujonin (en.dennisit) </a> Copy right since 2013-10-17 02:22:07
*
* @param member
* Updated data
* @throws Exception
* Update exception
*/
public void Updatemulti (member member) throws Exception {
Update update = new update ();
if (Null==member.getid () | | "". Equals (Member.getid (). Trim ())) {
If the primary key is empty, no modification is made
throw new Exception ("Update data Id is Null");
}
if (Stringutil.isnotnullvalue (Member.getusername ())) {
Update.set ("username", member.getusername ());
}
if (Stringutil.isnotnullvalue (Member.getpassword ())) {
Update.set ("Password", Member.getpassword ());
}
if (Stringutil.isnotnullvalue (Member.getsex ())) {
Update.set ("Sex", member.getsex ());
}
if (Stringutil.isnotnullvalue (Member.getemail ())) {
Update.set ("Email", member.getemail ());
}
This.updatemulti (Query.query (Criteria.where ("_id"). Is (Member.getid ()), update);
}
/**
* Implement Hook method, return the type of reflection
* @author <a href= ' mailto:dennisit@163.com ' >cn Sujonin (en.dennisit) </a> Copy right since 2013-10-17
*
* @return
* Reflection Type
*/
@Override
Protected class<member> Getentityclass () {
return member.class;
}
}
The business layer invokes DAO for the interaction of business data. Here is a list of the implementation of the persistence layer paging operation in the service layer in the instance
/**
* Paging Query
* @author <a href= ' mailto:dennisit@163.com ' >cn Sujonin (en.dennisit) </a> Copy right since 2013-10-17
*
* @param member
* Condition of the query
* @param start
* Corresponding <code>Page</code> Tool class properties current page: Pagenum
* @param size
* Corresponding <code>Page</code> tool class attributes How many records are displayed per page: pageSize
* @return
*/
Public page<member> querypage (member, int start, int size) {
page<member> page = new page<member> ();
try {
list<member> list = this.memberDao.queryPage (member, start, size);
Long recordtotal = This.memberDao.queryPageCount (member);
page= New page<member> (list, recordtotal, (long) start, size);
Log.info (page);
catch (Exception e) {
E.printstacktrace ();
}
return page;
}
At this point, SPRINGMVC consolidates the advanced operations instance of MongoDB and uses jquery in the instance. Pager plugin paging. This belongs to the application of paging plug-ins, it is not introduced.
Run Effect chart: