使用Spring Data来操作MongoDB
http://www.open-open.com/lib/view/open1342877356974.html
MongoDB 是一个可扩展的、高性能的、开源的NoSQL数据库,跟传统的数据库不一样,MongoDB并不是将数据存储在表中,他将数据结构化为一个类似于JSON的文档中。这篇文章就是展示如何使用Java基于MongoDB和Spring Data创建一个CRUD应用。
Spring Data for MongoDB
Spring Data for MongoDB提供了一个类似于基于Sping编程模型的NoSQL数据存储。Spring Data for MongoDB提供了很多特性,它使很多MongoDB的Java开发者解放了很多。MongoTemplate helper类支持通用的Mongo操作。它整合了文档和POJO之间的对象映射。通常,他会转换数据库访问异常到Spring中的异常结构。使用起来非常的方便。
你可以点击这里下载。
五步安装MongoDB
最清楚的安装步骤当然是MongoDB官方的安装说明了。安装说明。
- 下载最新的MongoDB。
- 解压到指定目录(这也算一步...)
- MongoDB需要一个存储文件的地方,Windows下默认的路径是C:\data\db。但是我们可以指定。例如我指定下面的路径1
<strong>C:\mongodb\data\db</strong> - 到C:\mongodb\bin 文件夹下执行如下命令。1
C:\mongodb\bin\mongod.exe –dbpath C:\mongodb\data\db如果你的路径包含空格,请使用双引号引起来。
- 到C:\mongodb\bin文件夹下,执行mongo.exe。默认的,mongo脚本将会监听localhost的27017端口。如果想将MongoDB作为windows的服务运行,点击这里。
到这里MongoDB的安装就完成了,接下来使用java搞CRUD。
五步使用Spring Data创建一个应用。
- 使用@Document注解指明一个领域对象将被持久化到MongoDB中。@Id注解identifies。12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
packagecom.orangeslate.naturestore.domain;importorg.springframework.data.annotation.Id;importorg.springframework.data.mongodb.core.mapping.Document;@DocumentpublicclassTree {@IdprivateString id;privateString name;privateString category;privateintage;publicTree(String id, String name,intage) {this.id = id;this.name = name;this.age = age;}publicString getId() {returnid;}publicvoidsetId(String id) {this.id = id;}publicString getName() {returnname;}publicvoidsetName(String name) {this.name = name;}publicString getCategory() {returncategory;}publicvoidsetCategory(String category) {this.category = category;}publicintgetAge() {returnage;}publicvoidsetAge(intage) {this.age = age;}@OverridepublicString toString() {return"Person [id="+ id +", name="+ name +", age="+ age+", category="+ category +"]";}} - 创建一个简单的接口。创建一个简单的接口,这个接口带有CRUD方法。这里我还带有createCollection方法和dropCollection方法。12345678910111213141516171819202122
packagecom.orangeslate.naturestore.repository;importjava.util.List;importcom.mongodb.WriteResult;publicinterfaceRepository<T> {publicList<T> getAllObjects();publicvoidsaveObject(T object);publicT getObject(String id);publicWriteResult updateObject(String id, String name);publicvoiddeleteObject(String id);publicvoidcreateCollection();publicvoiddropCollection();} - 创建一个指定的领域对象CRUD的实现。123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
packagecom.orangeslate.naturestore.repository;importjava.util.List;importorg.springframework.data.mongodb.core.MongoTemplate;importorg.springframework.data.mongodb.core.query.Criteria;importorg.springframework.data.mongodb.core.query.Query;importorg.springframework.data.mongodb.core.query.Update;importcom.mongodb.WriteResult;importcom.orangeslate.naturestore.domain.Tree;publicclassNatureRepositoryImplimplementsRepository<Tree> {MongoTemplate mongoTemplate;publicvoidsetMongoTemplate(MongoTemplate mongoTemplate) {this.mongoTemplate = mongoTemplate;}/*** Get all trees.*/publicList<Tree> getAllObjects() {returnmongoTemplate.findAll(Tree.class);}/*** Saves a {<span class="referer">@link</span> Tree}.*/publicvoidsaveObject(Tree tree) {mongoTemplate.insert(tree);}/*** Gets a {<span class="referer">@link</span> Tree} for a particular id.*/publicTree getObject(String id) {returnmongoTemplate.findOne(newQuery(Criteria.where("id").is(id)),Tree.class);}/*** Updates a {<span class="referer">@link</span> Tree} name for a particular id.*/publicWriteResult updateObject(String id, String name) {returnmongoTemplate.updateFirst(newQuery(Criteria.where("id").is(id)),Update.update("name", name), Tree.class);}/*** Delete a {<span class="referer">@link</span> Tree} for a particular id.*/publicvoiddeleteObject(String id) {mongoTemplate.remove(newQuery(Criteria.where("id").is(id)), Tree.class);}/*** Create a {<span class="referer">@link</span> Tree} collection if the collection does not already* exists*/publicvoidcreateCollection() {if(!mongoTemplate.collectionExists(Tree.class)) {mongoTemplate.createCollection(Tree.class);}}/*** Drops the {<span class="referer">@link</span> Tree} collection if the collection does already exists*/publicvoiddropCollection() {if(mongoTemplate.collectionExists(Tree.class)) {mongoTemplate.dropCollection(Tree.class);}}} - 创建Spring context。将所有spring beans和mongodb对象都声明在Spring context文件中,这里创建的是applicationContext.xml文件。注意到我们并没有创建一个叫做"nature"的数据库。在第一次存储数据的时候MongoDB将会为我们创建这个数据库。1234567891011121314151617181920212223242526272829303132333435363738
<?xmlversion="1.0"encoding="UTF-8"?><beansxmlns="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/beanshttp://www.springframework.org/schema/beans/spring-beans-3.0.xsdhttp://www.springframework.org/schema/contexthttp://www.springframework.org/schema/context/spring-context-3.0.xsd"><beanid="natureRepository"class="com.orangeslate.naturestore.repository.NatureRepositoryImpl"><propertyname="mongoTemplate"ref="mongoTemplate"/></bean><beanid="mongoTemplate"class="org.springframework.data.mongodb.core.MongoTemplate"><constructor-argname="mongo"ref="mongo"/><constructor-argname="databaseName"value="nature"/></bean><!-- Factory bean that creates the Mongo instance --><beanid="mongo"class="org.springframework.data.mongodb.core.MongoFactoryBean"><propertyname="host"value="localhost"/><propertyname="port"value="27017"/></bean><!-- Activate annotation configured components --><context:annotation-config/><!-- Scan components for annotations within the configured package --><context:component-scanbase-package="com.orangeslate.naturestore"><context:exclude-filtertype="annotation"expression="org.springframework.context.annotation.Configuration"/></context:component-scan></beans> - 创建一个测试类。这里我已经创建了一个测试类,并通过ClassPathXmlApplicationContext来初始化他。12345678910111213141516171819202122232425262728293031323334353637383940414243
packagecom.orangeslate.naturestore.test;importorg.springframework.context.ConfigurableApplicationContext;importorg.springframework.context.support.ClassPathXmlApplicationContext;importcom.orangeslate.naturestore.domain.Tree;importcom.orangeslate.naturestore.repository.NatureRepositoryImpl;importcom.orangeslate.naturestore.repository.Repository;publicclassMongoTest {publicstaticvoidmain(String[] args) {ConfigurableApplicationContext context =newClassPathXmlApplicationContext("classpath:/spring/applicationContext.xml");Repository repository = context.getBean(NatureRepositoryImpl.class);// cleanup collection before insertionrepository.dropCollection();// create collectionrepository.createCollection();repository.saveObject(newTree("1","Apple Tree",10));System.out.println("1. "+ repository.getAllObjects());repository.saveObject(newTree("2","Orange Tree",3));System.out.println("2. "+ repository.getAllObjects());System.out.println("Tree with id 1"+ repository.getObject("1"));repository.updateObject("1","Peach Tree");System.out.println("3. "+ repository.getAllObjects());repository.deleteObject("2");System.out.println("4. "+ repository.getAllObjects());}}
最后,让我们以Java应用程序的方式运行这个示例,我们可以看到如下的输出。第一个方法存储了一个"Apple Tree"。第二个方法存储了一个"Orange Tree"。第三个方法通过id获取一个对象。第四个使用Peach Tree更新对象。最后一个方法删除了第二个对象。
1 2 3 4 5 | 1. [Person [id=1, name=Apple Tree, age=10, category=null]]2. [Person [id=1, name=Apple Tree, age=10, category=null], Person [id=2, name=Orange Tree, age=3, category=null]]Tree with id 1Person [id=1, name=Apple Tree, age=10, category=null]3. [Person [id=1, name=Peach Tree, age=10, category=null], Person [id=2, name=Orange Tree, age=3, category=null]]4. [Person [id=1, name=Peach Tree, age=10, category=null]] |
注:可以在GitHub上下载到源码。
如本文存在任何侵权部分,请及时告知,我会第一时间删除!
转载本博客原创文章,请附上原文@cnblogs的网址!
QQ: 5854165 我的开源项目 欢迎大家一起交流编程架构技术&大数据技术! +++++++++++++++++++++++++++++++++++++++++++
浙公网安备 33010602011771号