使用MongoDB和Spring Data创建一个简单的Java 的CRUD应用
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 文件夹下执行如下命令。
1C:\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。
01packagecom.orangeslate.naturestore.domain;0203importorg.springframework.data.annotation.Id;04importorg.springframework.data.mongodb.core.mapping.Document;0506@Document07publicclassTree {0809@Id10privateString id;1112privateString name;1314privateString category;1516privateintage;1718publicTree(String id, String name,intage) {19this.id = id;20this.name = name;21this.age = age;22}2324publicString getId() {25returnid;26}2728publicvoidsetId(String id) {29this.id = id;30}3132publicString getName() {33returnname;34}3536publicvoidsetName(String name) {37this.name = name;38}3940publicString getCategory() {41returncategory;42}4344publicvoidsetCategory(String category) {45this.category = category;46}4748publicintgetAge() {49returnage;50}5152publicvoidsetAge(intage) {53this.age = age;54}5556@Override57publicString toString() {58return"Person [id="+ id +", name="+ name +", age="+ age59+", category="+ category +"]";60}61} -
创建一个简单的接口。创建一个简单的接口,这个接口带有CRUD方法。这里我还带有createCollection方法和dropCollection方法。
01packagecom.orangeslate.naturestore.repository;0203importjava.util.List;0405importcom.mongodb.WriteResult;0607publicinterfaceRepository<T> {0809publicList<T> getAllObjects();1011publicvoidsaveObject(T object);1213publicT getObject(String id);1415publicWriteResult updateObject(String id, String name);1617publicvoiddeleteObject(String id);1819publicvoidcreateCollection();2021publicvoiddropCollection();22} -
创建一个指定的领域对象CRUD的实现。
01packagecom.orangeslate.naturestore.repository;0203importjava.util.List;0405importorg.springframework.data.mongodb.core.MongoTemplate;06importorg.springframework.data.mongodb.core.query.Criteria;07importorg.springframework.data.mongodb.core.query.Query;08importorg.springframework.data.mongodb.core.query.Update;0910importcom.mongodb.WriteResult;11importcom.orangeslate.naturestore.domain.Tree;1213publicclassNatureRepositoryImplimplementsRepository<Tree> {1415MongoTemplate mongoTemplate;1617publicvoidsetMongoTemplate(MongoTemplate mongoTemplate) {18this.mongoTemplate = mongoTemplate;19}2021/**22* Get all trees.23*/24publicList<Tree> getAllObjects() {25returnmongoTemplate.findAll(Tree.class);26}2728/**29* Saves a {<a href="http://my.oschina.net/link1212" class="referer" target="_blank">@link</a> Tree}.30*/31publicvoidsaveObject(Tree tree) {32mongoTemplate.insert(tree);33}3435/**36* Gets a {<a href="http://my.oschina.net/link1212" class="referer" target="_blank">@link</a> Tree} for a particular id.37*/38publicTree getObject(String id) {39returnmongoTemplate.findOne(newQuery(Criteria.where("id").is(id)),40Tree.class);41}4243/**44* Updates a {<a href="http://my.oschina.net/link1212" class="referer" target="_blank">@link</a> Tree} name for a particular id.45*/46publicWriteResult updateObject(String id, String name) {47returnmongoTemplate.updateFirst(48newQuery(Criteria.where("id").is(id)),49Update.update("name", name), Tree.class);50}5152/**53* Delete a {<a href="http://my.oschina.net/link1212" class="referer" target="_blank">@link</a> Tree} for a particular id.54*/55publicvoiddeleteObject(String id) {56mongoTemplate57.remove(newQuery(Criteria.where("id").is(id)), Tree.class);58}5960/**61* Create a {<a href="http://my.oschina.net/link1212" class="referer" target="_blank">@link</a> Tree} collection if the collection does not already62* exists63*/64publicvoidcreateCollection() {65if(!mongoTemplate.collectionExists(Tree.class)) {66mongoTemplate.createCollection(Tree.class);67}68}6970/**71* Drops the {<a href="http://my.oschina.net/link1212" class="referer" target="_blank">@link</a> Tree} collection if the collection does already exists72*/73publicvoiddropCollection() {74if(mongoTemplate.collectionExists(Tree.class)) {75mongoTemplate.dropCollection(Tree.class);76}77}78} -
创建Spring context。将所有spring beans和mongodb对象都声明在Spring context文件中,这里创建的是applicationContext.xml文件。注意到我们并没有创建一个叫做"nature"的数据库。在第一 次存储数据的时候MongoDB将会为我们创建这个数据库。
01<?xmlversion="1.0"encoding="UTF-8"?>02<beansxmlns="http://www.springframework.org/schema/beans"03xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xmlns:context="http://www.springframework.org/schema/context"04xsi:schemaLocation="http://www.springframework.org/schema/beans0506http://www.springframework.org/schema/beans/spring-beans-3.0.xsd070809http://www.springframework.org/schema/context1011http://www.springframework.org/schema/context/spring-context-3.0.xsd">1213<beanid="natureRepository"14class="com.orangeslate.naturestore.repository.NatureRepositoryImpl">15<propertyname="mongoTemplate"ref="mongoTemplate"/>16</bean>1718<beanid="mongoTemplate"class="org.springframework.data.mongodb.core.MongoTemplate">19<constructor-argname="mongo"ref="mongo"/>20<constructor-argname="databaseName"value="nature"/>21</bean>2223<!-- Factory bean that creates the Mongo instance -->24<beanid="mongo"class="org.springframework.data.mongodb.core.MongoFactoryBean">25<propertyname="host"value="localhost"/>26<propertyname="port"value="27017"/>27</bean>2829<!-- Activate annotation configured components -->30<context:annotation-config/>3132<!-- Scan components for annotations within the configured package -->33<context:component-scanbase-package="com.orangeslate.naturestore">34<context:exclude-filtertype="annotation"35expression="org.springframework.context.annotation.Configuration"/>36</context:component-scan>3738</beans> -
创建一个测试类。这里我已经创建了一个测试类,并通过ClassPathXmlApplicationContext来初始化他。
01packagecom.orangeslate.naturestore.test;0203importorg.springframework.context.ConfigurableApplicationContext;04importorg.springframework.context.support.ClassPathXmlApplicationContext;0506importcom.orangeslate.naturestore.domain.Tree;07importcom.orangeslate.naturestore.repository.NatureRepositoryImpl;08importcom.orangeslate.naturestore.repository.Repository;0910publicclassMongoTest {1112publicstaticvoidmain(String[] args) {1314ConfigurableApplicationContext context =newClassPathXmlApplicationContext(15"classpath:/spring/applicationContext.xml");1617Repository repository = context.getBean(NatureRepositoryImpl.class);1819// cleanup collection before insertion20repository.dropCollection();2122// create collection23repository.createCollection();2425repository.saveObject(newTree("1","Apple Tree",10));2627System.out.println("1. "+ repository.getAllObjects());2829repository.saveObject(newTree("2","Orange Tree",3));3031System.out.println("2. "+ repository.getAllObjects());3233System.out.println("Tree with id 1"+ repository.getObject("1"));3435repository.updateObject("1","Peach Tree");3637System.out.println("3. "+ repository.getAllObjects());3839repository.deleteObject("2");4041System.out.println("4. "+ repository.getAllObjects());42}43}
最后,让我们以Java应用程序的方式运行这个示例,我们可以看到如下的输出。第一个方法存储了一个"Apple Tree"。第二个方法存储了一个"Orange Tree"。第三个方法通过id获取一个对象。第四个使用Peach Tree更新对象。最后一个方法删除了第二个对象。
1 1. [Person [ id =1, name=Apple Tree, age=10, category=null]]
2 2. [Person [ id =1, name=Apple Tree, age=10, category=null], Person [ id =2, name=Orange Tree, age=3, category=null]]
3 Tree with id 1Person [ id =1, name=Apple Tree, age=10, category=null]
4 3. [Person [ id =1, name=Peach Tree, age=10, category=null], Person [ id =2, name=Orange Tree, age=3, category=null]]
5 4. [Person [ id =1, name=Peach Tree, age=10, category=null]]
注:可以在GitHub上下载到源码 。
OSChina.NET 原创翻译/原文链接 。
http://www.oschina.net/question/82993_61815?from=20120729