There is an article in the previous record that without using spring, it directly connects and operates the mongodb database in Java code. Here we will record that when using spring, simple operation of mongodb in Java.
Maven package configuration:
Because it involves spring and springmvc, 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> <version>3.0.3</version> </dependency> <dependency> <groupId>commons-logging</groupId> <artifactId>commons-logging</artifactId> <version>1.2</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-test</artifactId> <version>4.1.6.RELEASE</version> </dependency> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.11</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context</artifactId> <version>4.1.7.RELEASE</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context-support</artifactId> <version>4.0.9.RELEASE</version> </dependency> </dependency> <build> <plugins> <plugin> <artifactId>maven-compiler-plugin</artifactId> <version>2.3.2</version> <configuration> <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</bootclasspath> </compilerArguments> </configuration> </plugin> </plugins> <finalName>spring_mongo</finalName> </build> </project> Spring basic configuration:
Mainly, it is to enable annotation scanning, 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/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd http://www.springframework.org/schema/task http://www.springframework.org/schema/task http://www.springframework.org/schema/task/spring-task-3.1.xsd"> <!-- Automatic scan (auto-injection) --> <context:component-scan base-package="spring_mogo.dao.daoImp" /> <!-- Import mongodb's configuration file --> <import resource="spring-mongodb305.xml" /> <!-- Turn on annotation--> <context:annotation-config /> </beans>
Spring connects mongodb and establishes configurations for related factories:
<?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.springframework.org/schema/data/mongo http://www.springframework.org/schema/data/mongo/spring-mongo.xsd"> <!-- spring configuration for connecting to mongodb database --> <mongo:mongo-client host="192.168.0.201" port="27017" credentials="tuzongxun:123456@mongoTest" id="mongo"> <mongo:client-options write-concern="SAFE"/> </mongo:mongo-client> <mongo:db-factory id="mongoDbFactory" dbname="mongoTest" mongo-ref="mongo" /> <!-- Just use this to call the corresponding method --> <bean id="mongoTemplate"> <constructor-arg name="mongoDbFactory" ref="mongoDbFactory" /> </bean> </beans>
The entity class corresponding to the database:
It should be noted that the serialized interface needs to be implemented and the uid attribute is set, otherwise the database return result cannot be converted directly into object attributes during 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; } } Obtain MongoTemplete that operates mongodb according to spring configuration, and you need to implement the 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 Set mongoTemplate according to the configuration file * @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 to operate the database and the corresponding implementation class:
The most basic addition, deletion, modification and search are demonstrated. What should be paid attention to is the declaration of parameters and the conversion of the entity class when receiving the returned data:
(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 13, 2016 3:07:39 PM * @throws */ public List<UserModel> findAll(); /** * New data* * @author: tuzongxun * @Title: insertUser * @param @param user * @return void * @date May 13, 2016 3:09:45 PM * @throws */ public void insertUser(UserModel user); /** * Delete data* * @author: tuzongxun * @Title: removeUser * @param @param userName * @return void * @date May 13, 2016 3:09:55 PM * @throws */ public void removeUser(String userName); /** * Modify data* * @author: tuzongxun * @Title: updateUser * @param @param user * @return void * @date May 13, 2016 3:10:06 PM * @throws */ public void updateUser(UserModel user); /** * Query by condition* * @author: tuzongxun * @Title: findForRequery * @param * @return void * @date May 13, 2016 3:23:37 PM * @throws */ public List<UserModel> findForRequery(String userName); } (2) Implementation class, here we need to inherit the AbstractBaseMongoTemplete class, so as 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 13, 2016 3:10:29 PM * @throws */ @Override public List<UserModel> findAll() { // The corresponding corpse class and corresponding collection name of the collection need to be set, so that the query result is directly mapped List<UserModel> userList = mongoTemplate.findAll(UserModel.class, "user"); return userList; } /** * New data* * @author: tuzongxun * @Title: insertUser * @Description: TODO * @param @param user * @date May 13, 2016 3:10:45 PM * @throws */ @Override public void insertUser(UserModel user) { // Set the document object that needs to be inserted into the database DBObject object = new BasicDBObject(); object.put("userName", user.getUserName()); object.put("password", user.getPassword()); mongoTemplate.insert(object, "user"); } /** * Delete data according to conditions* * @author: tuzongxun * @Title: removeUser * @Description: TODO * @param @param userName * @date May 13, 2016 3:11:01 PM * @throws */ @Override public void removeUser(String userName) { // Set the delete condition, delete all Query query = new Query(); Criteria criteria = new Criteria("userName"); criteria.is(userName); query.addCriteria(criteria); mongoTemplate.remove(query, "user"); } /** * Modify data* * @author: tuzongxun * @Title: updateUser * @Description: TODO * @param @param user * @date May 13, 2016 3:11:12 PM * @throws */ @Override public void updateUser(UserModel user) { // Set modification conditions Query query = new Query(); Criteria criteria = new Criteria("userName"); criteria.is(user.getUserName()); query.addCriteria(criteria); // Set modification content Update update = Update.update("password", user.getPassword()); // Parameters: query conditions, change the result, collection name mongoTemplate.updateFirst(query, update, "user"); } /** * Query based on the condition * * @author: tuzongxun * @Title: findForRequery * @Description: TODO * @param @param userName * @date May 13, 2016 4:08:15 PM * @throws */ @Override public List<UserModel> findForRequery(String userName) { Query query = new Query(); Criteria criteria = new Criteria("userName"); criteria.is(userName); query.addCriteria(criteria); // Query condition, entity class corresponding to the set, set name List<UserModel> userList = mongoTemplate.find(query, UserModel.class, "user"); return userList; } } Test class:
In order 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, 2016 3:27:51 PM * @throws */ @Test public void monFindTest() { List<UserModel> userModels = userDao.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 13, 2016 3:27:38 PM * @throws */ @Test public void monInsertTest() { UserModel user = new UserModel("test111", "123456"); userDao.insertUser(user); this.monFindTest(); } /** * Delete test* * @author: tuzongxun * @Title: monRemoveTest * @param * @return void * @date May 13, 2016 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 May 13, 2016 3:50:08 PM * @throws */ @Test public void monUpdateTest() { UserModel user = new UserModel("test111", "test"); userDao.updateUser(user); this.monFindTest(); } /** * Query by condition* * @author: tuzongxun * @Title: monFindForRuq * @param * @return void * @date May 13, 2016 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()); } } } } Download the demo in the later stage: demo
The above is all the content of this article. I hope it will be helpful to everyone's learning and I hope everyone will support Wulin.com more.