安装Spring for Mongodb
Spring项目为方便对Mongodb的操作,建立了spring-data的子项目,地址在:
http://www.springsource.org/spring-data/mongodb,目前版本是1.0.0M2阶段,已支持对 Mongodb的一系列基本操作。我们先从http://www.springsource.org/spring-data/mongodb中下载相关 的包:spring-data-document-1.0.0.M2.zip,下载解压后,将解压后的四个JAR文件放到工程路径的lib库中,本文中还 将使用Spring 3.0.4的版本,请读者自行下载配置。
Spring Mongodb的配置
目前,可以有两种方式对Spring mongodb进行配置。第一种是使用Spring 3中的注解,另外一种是使用传统的XML配置。下面分别进行讲解:
使用Spring 3中的注解
首先在配置类中,要继承AbstractMongoConfiguration类,代码如下:
- 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 {
- returnnewMongo("localhost");
- }
- @Override
- public@Bean MongoTemplate mongoTemplate() throwsException {
- returnnewMongoTemplate(mongo(),"yourdb","yourCollection");
- }
- }
这里,引入了MongoTemplate模版类,并且使用对连接数据库的地址,数据库名和collection进行了初始化。
在调用Spring Mongodb配置时,只需要在需要使用的类中调用AnnotationConfigApplicationContext,传入刚才配置好的SpringMongoConfig类即可。如下代码所示:
ctx =newAnnotationConfigApplicationContext(SpringMongoConfig.class);
MongoOperations
mongoOperation =(MongoOperations)ctx.getBean("mongoTemplate");
当获得了mongoOperation对象的实例后,即可进行对mongodb的相关操作。
使用XML配置文件
使用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">
- <!--Default bean name is 'mongo' -->
- <mongo:mongo host="localhost"port="27017"/>
- <bean id="mongoTemplate"
- class="org.springframework.data.document.mongodb.MongoTemplate">
- <constructor-arg ref="mongo"/>
- <constructor-arg name="databaseName"value="yourdb"/>
- <constructor-arg name="defaultCollectionName"value="yourCollection"/>
- </bean>
- <!--To translate any MongoExceptions thrown in @Repository annotated classes -->
- <context:annotation-config />
- </beans>
注意这里引用相关的命名空间xmlns:mongo="http://www.springframework.org/schema/data/mongo"
,并且在名为mongoTemplate中注入相关的数据库地址,数据库名即可,使用方法如下:
使用Spring Mongodb实现增删改查操作
下面通过实例讲解如何使用Spring Mongodb实现增删改查操作,假设我们现在有一个实
体类user如下:
- packagecom.mkyong.user;
- publicclassUser {
- privateString id;
- privateString firstname;
- privateString lastname;
- privateintage;
- //getter and setter methods
- }
接下来,我们看具体的操作代码,如下,这里假设要将user类保存到名为userprofile的数据集中。
- packagecom.mkyong.core;
- importjava.util.List;
- importorg.springframework.context.ApplicationContext;
- importorg.springframework.context.annotation.AnnotationConfigApplicationContext;
- importorg.springframework.context.support.GenericXmlApplicationContext;
- importorg.springframework.data.document.mongodb.MongoOperations;
- importorg.springframework.data.document.mongodb.query.Criteria;
- importorg.springframework.data.document.mongodb.query.Query;
- importorg.springframework.data.document.mongodb.query.Update;
- importcom.mkyong.config.SpringMongoConfig;
- importcom.mkyong.user.User;
- publicclassApp
- {
- publicstaticvoidmain( String[] args )
- {
- ApplicationContext ctx =newAnnotationConfigApplicationContext(SpringMongoConfig.class);
- MongoOperations mongoOperation =(MongoOperations)ctx.getBean("mongoTemplate");
- User user =newUser("1001", "yong", "mook kim", 30);
- //保存
- mongoOperation.save("userprofile",user);
- //查找
- User savedUser =mongoOperation.findOne("userprofile",
- newQuery(Criteria.where("id").is("1001")),
- User.class);
- System.out.println("savedUser : "+savedUser);
- //更新
- mongoOperation.updateFirst("userprofile",
- newQuery(Criteria.where("firstname").is("yong")),
- Update.update("lastname", "new lastname"));
- User updatedUser =mongoOperation.findOne("userprofile",
- newQuery(Criteria.where("id").is("1001")),
- User.class);
- System.out.println("updatedUser : "+updatedUser);
- //删除
- mongoOperation.remove("userprofile",
- newQuery(Criteria.where("id").is("1001")),
- User.class);
- //显示当前列表
- List<User>listUser =
- mongoOperation.getCollection("userprofile", User.class);
- System.out.println("Number of user = "+listUser.size());
- }
- }
输出结果如下:
updatedUser : User [id=1001, firstname=yong, lastname=newlastname, age=30]
Number of user =
Spring mongodb插入数据
下面详细讲解如何使用spring mongodb插入数据。在spring mongodb中,插入数据到
mongodb有如下几种方法:
- User user =newUser("...");
- //将user对象保存到"user"这个collection中
- mongoOperation.save(user);
- //将user对象保存到"new collection"这个collection中
- mongoOperation.save("new collection",user);
- //将user对象保存到"user"这个collection中
- mongoOperation.insert(user);
- //将user对象保存到"new collection"这个collection中
- mongoOperation.insert("new collection", user);
- //将user的对象列表(List)保存到"user"collection中去
- mongoOperation.insertList(userInList);
- //将user的对象列表(List)保存到"new collection"collection中去
- mongoOperation.insertList("new collection", userInList);
要注意的是,Spring mongodb中,当没有指定collection时,就会把对象保存到以对象命名的collection中。比如上例中的 mongoOperation.insert(user),由于没指定collection的名称,所以会把user对象保存到user这个新建立的 collection中。
另外请注意其中的save和insert的区别。它们的区别为:
1)save意思是,当记录不存在时插入,或者是当记录已存在是更新,实际上就是saveorupdate的意思。
2) insert的意思是:当记录不存在时插入,而如果记录存在时则忽略,继续插入。
下面举例子说明:
- 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 {
- publicstaticvoidmain(String[] args) {
- ApplicationContext ctx =newAnnotationConfigApplicationContext(
- SpringMongoConfig.class);
- MongoOperations mongoOperation =(MongoOperations) ctx
- .getBean("mongoTemplate");
- //新增一个user对象,并把它放到"ABC"这个collection中
- System.out.println("Case 1...");
- User userA =newUser("1111", "user", "A", 99);
- mongoOperation.save("ABC", userA);
- //查找刚插入的user对象
- User userA1 =mongoOperation.findOne("ABC",
- newQuery(Criteria.where("id").is("1111")), User.class);
- System.out.println(userA1);
- //插入新的user,放到userB这个collection中去
- System.out.println("Case 2...");
- User userB =newUser("2222", "user", "B", 99);
- mongoOperation.save(userB);
- //查找
- User userB1 =mongoOperation.findOne(
- newQuery(Criteria.where("id").is("2222")), User.class);
- System.out.println(userB1);
- //插入对象列表,放到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);
- List<User>userList =newArrayList<User>();
- userList.add(userC);
- userList.add(userD);
- userList.add(userE);
- mongoOperation.insertList("ABC-List", userList);
- List<User>users =mongoOperation.find("ABC-List", newQuery(Criteria
- .where("firstname").is("user")), User.class);
- for(User temp : users) {
- System.out.println(temp);
- }
- }
- }
输出结果如下:
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]
更新Document
在mongodb中,可以使用save,updateFirst(),updateMulti()方法来进行更新,下面
是相关的例子
- publicclassApp {
- publicstaticvoidmain(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);
- //修改user对象的lastname
- user.setLastname("new last name");
- //更新user对象
- 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");
- //将id为1000的user对象的firstname属性的值更新为”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);
- //对id为1000的user的age加上10
- 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);
- }
- }
结果为:
User [id=1000, firstname=user-first, lastname=user-last, age=17]
User [id=1000, firstname=user-first, lastname=newlast name, age=17]
Case 2...by updateFirst()-$set
User [id=1000, firstname=newfirst name, lastname=newlast name, age=17]
Case 3...by updateFirst()-$inc
User [id=1000, firstname=newfirst name, lastname=newlast name, age=27]
此外,还支持使用updateMulti,updateMulti是将所有的对象进行更新,比如:
newQuery(Criteria.where("firstname").is("yong")),
Update.update("age",40));
表示将所有firstname为yong的user对象的age属性全部更新为40。
查询Document
在spring mongodb中,可以使用findOne(),find()和getCollection()去查询mongodb,常见的用法如下:
- User user =newUser("...");
- //找到第一个id=1001的user对象
- User user =mongoOperation.findOne("test", newQuery(Criteria
- .where("id").is("1001")), User.class);
- //从test集合中获得所有id<=1000并且age=21的user对象
- List<User>users =mongoOperation.find("test", newQuery(Criteria
- .where("id").lte("2001").and("age").is(21)), User.class);
- //从test 集合中获得所有的user对象列表
- List<User>users =mongoOperation.getCollection("test", User.class);
删除document
在spring mongodb中, 删除document使用remove方法,示例如下:
- User user =newUser("...");
- //删除user集合中的user对象
- mongoOperation.remove(user);
- //删除test集合下的id=2的user对象
- mongoOperation.remove("test", newQuery(Criteria
- .where("id").is("2")));
- //删除test集合下的,id=3的user对象,最后并且返回这个被删除的对象
- User deletedUser =mongoOperation.findAndRemove("test",
- newQuery(Criteria.where("id").is("3")), User.class);