spring 就是NB,很快找到spring配置mongodb的解决方案:spring-data
本文如题,让我们轻松通过spring来管理mongodb的各种操作。
该文章主要参考spring的官方实例文档:spring-data-mongodb-hello-world-example:http://www.mkyong.com/mongodb/spring-data-mongodb-hello-world-example/
想看原著的同学可以借鉴哈,写的相当不错!
我们可以通过Spring Data for MongoDB 框架的两种方式来配置mongodb: XML配置文件 and 注解(annotation)来进行CRUD 操作
使用工具:
- Spring Data MongoDB – 1.0.0.M2
- Spring Core – 3.0.5.RELEASE
- Java Mongo Driver – 2.5.2
- Eclipse – 3.5
- JDK – 1.6
- Maven2
该项目源码是spring官方提供的,可通过maven来构建项目,使用起来非常方便!哥们的附件里会提供源码供大家下载。
不过现在maven还没有引入mongodb相关的jar文件,所以请在http://www.springsource.org/spring-data/mongodb自行下载并引入项目,附件里我也会给大家提供。
如果你已经把源码准备好了,现在我们继续:
一,通过spring有两种方式引入mongodb:
1.通过注解(Annotation):
文件:SpringMongoConfig.java
package com.mkyong.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.document.mongodb.MongoTemplate;
import org.springframework.data.document.mongodb.config.AbstractMongoConfiguration;
import com.mongodb.Mongo;
/**
* Spring MongoDB configuration file
*
*/
@Configuration
public class SpringMongoConfig extends AbstractMongoConfiguration {
@Override
public @Bean Mongo mongo() throws Exception {
return new Mongo("localhost");
}
@Override
public @Bean MongoTemplate mongoTemplate() throws Exception {
return new MongoTemplate(mongo(),"yourdb","yourCollection");
}
}
慢慢发现通过注解配置这些还是很方便的,不常改的配置直接写类里而不麻烦xml配置文件不是很爽?
使用的时候也非常方便:
ApplicationContext ctx = new AnnotationConfigApplicationContext(SpringMongoConfig.class);
MongoOperations mongoOperation = (MongoOperations)ctx.getBean("mongoTemplate");
相信大家都能看懂。
到这点你应该能发现MongoOperations 是主要干事的了
2.通过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>
标准的spring环境配置。
使用:
ApplicationContext ctx = new GenericXmlApplicationContext("mongo-config.xml");
二。使用模型:
User:
package com.mkyong.user;
public class User {
private String id;
private String firstname;
private String lastname;
private int age;
//getter and setter methods
}
不需要任何注解的!
三。CRUD操作:
Full example to show you how to use Spring data to perform CRUD operations in mongoDB. The “user” object is saved into a collection named “userprofile“, under “yourdb” database.
这个实例给大家展示了spring data通过mongoDB进行的CRUD 操作。"user"对象被操作在“userprofile“集合(可理解为表)中,“yourdb”数据库下。
package com.mkyong.core;
import java.util.List;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.support.GenericXmlApplicationContext;
import org.springframework.data.document.mongodb.MongoOperations;
import org.springframework.data.document.mongodb.query.Criteria;
import org.springframework.data.document.mongodb.query.Query;
import org.springframework.data.document.mongodb.query.Update;
import com.mkyong.config.SpringMongoConfig;
import com.mkyong.user.User;
public class App
{
public static void main( String[] args )
{
//For Annotation
ApplicationContext ctx = new AnnotationConfigApplicationContext(SpringMongoConfig.class);
//For XML
//ApplicationContext ctx = new GenericXmlApplicationContext("mongo-config.xml");
MongoOperations mongoOperation = (MongoOperations)ctx.getBean("mongoTemplate");
User user = new User("1001", "yong", "mook kim", 30);
//save
mongoOperation.save("userprofile",user);
//find
User savedUser = mongoOperation.findOne("userprofile",
new Query(Criteria.where("id").is("1001")),
User.class);
System.out.println("savedUser : " + savedUser);
//update
mongoOperation.updateFirst("userprofile",
new Query(Criteria.where("firstname").is("yong")),
Update.update("lastname", "new lastname"));
//find
User updatedUser = mongoOperation.findOne("userprofile",
new Query(Criteria.where("id").is("1001")),
User.class);
System.out.println("updatedUser : " + updatedUser);
//delete
mongoOperation.remove("userprofile",
new Query(Criteria.where("id").is("1001")),
User.class);
//List
List<User> listUser =
mongoOperation.getCollection("userprofile", User.class);
System.out.println("Number of user = " + listUser.size());
}
}
运行看看吧。。。
旅途愉快!