Install Spring for Mongodb
In order to facilitate the operation of Mongodb, the Spring project has established a sub-project of spring-data, the address is:
http://www.springsource.org/spring-data/mongodb, the current version is in the 1.0.0M2 stage, and already supports a series of basic operations on Mongodb. We first download the relevant package from http://www.springsource.org/spring-data/mongodb: spring-data-document-1.0.0.M2.zip, after downloading and decompressing, put The four decompressed JAR files are placed in the lib library of the project path, and Spring will also be used in this article
Version 3.0.4, please download the configuration by yourself.
Configuration of Spring Mongodb
Currently, there are two ways to configure Spring mongodb. The first is to use Spring
3, the other is to use traditional XML configuration. The following are the explanations:
Using annotations in Spring 3
First, in the configuration class, inherit the AbstractMongoConfiguration class,
packagecom.mkyong.config;
importorg.springframework.context.annotation.Bean;
importorg.springframework.context.annotation.Configuration;
importorg.springframework.data.document.mongodb.MongoTemplate;
importorg.springframework.data.document.mongodb.config.AbstractMongoConfiguration;
importcom.mongodb.Mongo;
/**
* Spring MongoDB configuration file
*
*/
@Configuration
publicclassSpringMongoConfig extendsAbstractMongoConfiguration {
@Override
public@Bean Mongo mongo() throwsException {
return newMongo(“localhost”);
}
@Override
public@Bean MongoTemplate mongoTemplate() throwsException {
return newMongoTemplate(mongo(),”yourdb”,”yourCollection”);
}
}
Here, the MongoTemplate template class is introduced, and the address to connect to the database, database name and collection are initialized.
In calling Spring
When configuring Mongodb, you only need to call AnnotationConfigApplicationContext in the class you need to use, and pass in the SpringMongoConfig class you just configured. As shown in the following code:
ApplicationContext
ctx
=newAnnotationConfigApplicationContext(SpringMongoConfig.class);
Mongo Operations
mOngoOperation=(MongoOperations)ctx.getBean(“mongoTemplate”);
After obtaining the instance of the mongoOperation object, you can perform related operations on mongodb.
Using an XML configuration file
The method of using the XML configuration file is as follows:
<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”>
<bean id="mongoTemplate"
class=”org.springframework.data.document.mongodb.MongoTemplate”>
Note that the relevant citations hereInsert, or ignore if the record exists, and continue inserting.
The following example illustrates:
packagecom.mkyong.core;
importjava.util.ArrayList;
importjava.util.List;
importorg.springframework.context.ApplicationContext;
importorg.springframework.context.annotation.AnnotationConfigApplicationContext;
importorg.springframework.data.document.mongodb.MongoOperations;
importorg.springframework.data.document.mongodb.query.Criteria;
importorg.springframework.data.document.mongodb.query.Query;
importcom.mkyong.config.SpringMongoConfig;
importcom.mkyong.user.User;
publicclassApp {
publicstatic voidmain(String[] args) {
ApplicationContext ctx = newAnnotationConfigApplicationContext(
SpringMongoConfig.class);
MongoOperations mongoOperation =(MongoOperations) ctx
.getBean(“mongoTemplate”);
//Add a new user object and put it in the collection “ABC”
System.out.println(“Case 1…”);
User userA =newUser(“1111”, “user”, “A”, 99);
mongoOperation. save(“ABC”, userA);
//Find the user object just inserted
User userA1 =mongoOperation. findOne(“ABC”,
newQuery(Criteria.where(“id”).is(“1111”)), User.class);
System.out.println(userA1);
//Insert a new user and put it in the collection of userB
System.out.println(“Case 2…”);
User userB =newUser(“2222”, “user”, “B”, 99);
mongoOperation. save(userB);
//find
User userB1 = mongoOperation. findOne(
newQuery(Criteria.where(“id”).is(“2222”)), User.class);
System.out.println(userB1);
//Insert the object list and put it in the arraylist
System.out.println(“Case 3…”);
User userC =newUser(“3333”, “user”, “C”, 99);
User userD =newUser(“4444”, “user”, “D”, 99);
User userE =newUser(“5555”, “user”, “E”, 99);
ListuserList =newArrayList();
userList.add(userC);
userList.add(userD);
userList.add(userE);
mongoOperation.insertList(“ABC-List”, userList);
Listusers =mongoOperation.find(“ABC-List”, newQuery(Criteria
.where(“firstname”).is(“user”)), User.class);
for(User temp : users) {
System.out.println(temp);
}
}
}
The output is as follows:
Case 1…
User [id=1111, firstname=user, lastname=A, age=99]
Case 2…
User [id=2222, firstname=user, lastname=B, age=99]
Case 3…
User [id=3333, firstname=user, lastname=C, age=99]
User [id=4444, firstname=user, lastname=D, age=99]
User [id=5555, firstname=user, lastname=E, age=99]
Update Document
In mongodb, you can use save, updateFirst(), updateMulti() methods to update, as follows
are related examples
publicclassApp {
publicstatic voidmain(String[] args) {
ApplicationContext ctx = newAnnotationConfigApplicationContext(
SpringMongoConfig.class);
MongoOperations mongoOperation =(MongoOperations) ctx
.getBean(“mongoTemplate”);
User user =newUser(“1000”, “user-first”, “user-last”, 17);
System.out.println(“Case 1…by save()”);
mongoOperation. save(user);
User userPrint1 =mongoOperation.findOne(newQuery(Criteria.where(“id”).is(“1000”)), User.class);
System.out.println(userPrint1);
//Modify the lastname of the user object
user.setLastname(“new last name”);
//Update user object
mongoOperation. save(user);
User userPrint2 = mongoOperation.findOne(newQuery(Criteria.where(“id”)
.is(“1000”)), User.class);
System.out.println(userPrint2);
//Case 2 … update firstname field, $set
System.out.println(“Case 2…by updateFirst() – $set”);
//Update the value of the firstname attribute of the user object with id 1000 to “new firstname”
mongoOperation. updateFirst(“user”,
newQuery(Criteria.where(“_id”).is(“1000”)),
Update. update(“firstname”, “new first name”));
User userPrint3 =mongoOperation.findOne(newQuery(Criteria.where(“id”)
.is(“1000”)), User.class);
System.out.println(userPrint3);
//Add 10 to the age of the user whose id is 1000
System.out.println(“Case 3…by updateFirst() – $inc”);
Update updateAge = newUpdate();
updateAge.inc(“age”, 10);
mongoOperation. updateFirst(“user”,
newQuery(Criteria.where(“_id”).is(“1000”)), updateAge);
User userPrint4 = mongoOperation. findOne(newQuery(Criteria
.where(“_id”).is(“1000”)), User.class);
System.out.println(userPrint4);
}
}
The result is:
Case 1…by save()
User [id=1000, firstname=user-first, lastname=user-last,
age=17]
User [id=1000, firstname=user-first, lastname=newlastname,
age=17]
Case 2…by updateFirst()-$set
User [id=1000, firstname=newfirstname, lastname=newlastname,
age=17]
Case 3…by updateFirst()-$inc
User [id=1000, firstname=newfirstname, lastname=newlastname,
age=27]
In addition, updateMulti is also supported, updateMulti is to update all objects, such as:
mongoOperation. updateMulti(“user”,
newQuery(Criteria.where(“firstname”).is(“yong”)),
Update. update(“age”,40));
Indicates to update the age attribute of all user objects whose firstname is yong to 40.
Query Document
in spring
In mongodb, you can use findOne(), find() and getCollection() to query mongodb. The common usage is as follows:
User user =newUser(“…”);
//Find the first user object with id=1001
User user = mongoOperation. findOne(“test”, newQuery(Criteria
.where(“id”).is(“1001”)), User.class);
//Get all user objects with id<=1000 and age=21 from the test collection
Listusers = mongoOperation. find(“test”, newQuery(Criteria
.where(“id”).lte(“2001”).and(“age”).is(21)), User.class);
// Get a list of all user objects from the test collection
Listusers =mongoOperation.getCollection(“test”, User.class);
Delete document
In spring mongodb, delete the document using the remove method, the example is as follows:
User user =newUser(“…”);
//Delete the user object in the user collection
mongoOperation. remove(user);
//Delete the user object with id=2 under the test collection
mongoOperation. remove(“test”, newQuery(Criteria
.where(“id”).is(“2”)));
//Delete the user object with id=3 under the test collection, and finally return the deleted object
User deletedUser = mongoOperation. findAndRemove(“test”,
newQuery(Criteria.where(“id”).is(“3”)), User.class);
rPrint3);
//Add 10 to the age of the user whose id is 1000
System.out.println(“Case 3…by updateFirst() – $inc”);
Update updateAge = newUpdate();
updateAge.inc(“age”, 10);
mongoOperation. updateFirst(“user”,
newQuery(Criteria.where(“_id”).is(“1000”)), updateAge);
User userPrint4 = mongoOperation. findOne(newQuery(Criteria
.where(“_id”).is(“1000”)), User.class);
System.out.println(userPrint4);
}
}
The result is:
Case 1…by save()
User [id=1000, firstname=user-first, lastname=user-last,
age=17]
User [id=1000, firstname=user-first, lastname=newlastname,
age=17]
Case 2…by updateFirst()-$set
User [id=1000, firstname=newfirstname, lastname=newlastname,
age=17]
Case 3…by updateFirst()-$inc
User [id=1000, firstname=newfirstname, lastname=newlastname,
age=27]
In addition, updateMulti is also supported, updateMulti is to update all objects, such as:
mongoOperation. updateMulti(“user”,
newQuery(Criteria.where(“firstname”).is(“yong”)),
Update. update(“age”,40));
Indicates to update the age attribute of all user objects whose firstname is yong to 40.
Query Document
in spring
In mongodb, you can use findOne(), find() and getCollection() to query mongodb. The common usage is as follows:
User user =newUser(“…”);
//Find the first user object with id=1001
User user = mongoOperation. findOne(“test”, newQuery(Criteria
.where(“id”).is(“1001”)), User.class);
//Get all user objects with id<=1000 and age=21 from the test collection
Listusers = mongoOperation. find(“test”, newQuery(Criteria
.where(“id”).lte(“2001”).and(“age”).is(21)), User.class);
// Get a list of all user objects from the test collection
Listusers =mongoOperation.getCollection(“test”, User.class);
Delete document
In spring mongodb, delete the document using the remove method, the example is as follows:
User user =newUser(“…”);
//Delete the user object in the user collection
mongoOperation. remove(user);
//Delete the user object with id=2 under the test collection
mongoOperation. remove(“test”, newQuery(Criteria
.where(“id”).is(“2”)));
//Delete the user object with id=3 under the test collection, and finally return the deleted object
User deletedUser = mongoOperation. findAndRemove(“test”,
newQuery(Criteria.where(“id”).is(“3”)), User.class);