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中的异常结构。使用起来非常的方便。
你可以点击这里下载。
五步使用Spring Data创建一个应用。
使用@Document注解指明一个领域对象将被持久化到MongoDB中。@Id注解identifies。
package com.orangeslate.naturestore.domain; import org.springframework.data.annotation.Id; import org.springframework.data.mongodb.core.mapping.Document; @Document public class Tree { @Id private String id; private String name; private String category; private int age; public Tree(String id, String name, int age) { this.id = id; this.name = name; this.age = age; } public String getId() { return id; } public void setId(String id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getCategory() { return category; } public void setCategory(String category) { this.category = category; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } @Override public String toString() { return "Person [id=" + id + ", name=" + name + ", age=" + age + ", category=" + category + "]"; } }
创建一个简单的接口。创建一个简单的接口,这个接口带有CRUD方法。这里我还带有createCollection方法和dropCollection方法。
package com.orangeslate.naturestore.repository; import java.util.List; import com.mongodb.WriteResult; public interface Repository<T> { public List<T> getAllObjects(); public void saveObject(T object); public T getObject(String id); public WriteResult updateObject(String id, String name); public void deleteObject(String id); public void createCollection(); public void dropCollection(); }
创建一个指定的领域对象CRUD的实现。
package com.orangeslate.naturestore.repository; import java.util.List; import org.springframework.data.mongodb.core.MongoTemplate; import org.springframework.data.mongodb.core.query.Criteria; import org.springframework.data.mongodb.core.query.Query; import org.springframework.data.mongodb.core.query.Update; import com.mongodb.WriteResult; import com.orangeslate.naturestore.domain.Tree; public class NatureRepositoryImpl implements Repository<Tree> { MongoTemplate mongoTemplate; public void setMongoTemplate(MongoTemplate mongoTemplate) { this.mongoTemplate = mongoTemplate; } /** * Get all trees. */ public List<Tree> getAllObjects() { return mongoTemplate.findAll(Tree.class); } /** * Saves a {<span class="referer">@link</span> Tree}. */ public void saveObject(Tree tree) { mongoTemplate.insert(tree); } /** * Gets a {<span class="referer">@link</span> Tree} for a particular id. */ public Tree getObject(String id) { return mongoTemplate.findOne(new Query(Criteria.where("id").is(id)), Tree.class); } /** * Updates a {<span class="referer">@link</span> Tree} name for a particular id. */ public WriteResult updateObject(String id, String name) { return mongoTemplate.updateFirst( new Query(Criteria.where("id").is(id)), Update.update("name", name), Tree.class); } /** * Delete a {<span class="referer">@link</span> Tree} for a particular id. */ public void deleteObject(String id) { mongoTemplate .remove(new Query(Criteria.where("id").is(id)), Tree.class); } /** * Create a {<span class="referer">@link</span> Tree} collection if the collection does not already * exists */ public void createCollection() { if (!mongoTemplate.collectionExists(Tree.class)) { mongoTemplate.createCollection(Tree.class); } } /** * Drops the {<span class="referer">@link</span> Tree} collection if the collection does already exists */ public void dropCollection() { if (mongoTemplate.collectionExists(Tree.class)) { mongoTemplate.dropCollection(Tree.class); } } }
创建Spring context。将所有spring beans和mongodb对象都声明在Spring context文件中,这里创建的是applicationContext.xml文件。注意到我们并没有创建一个叫做"nature"的数据库。在第一次存储数据的时候MongoDB将会为我们创建这个数据库。
<?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" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd"> <bean id="natureRepository" class="com.orangeslate.naturestore.repository.NatureRepositoryImpl"> <property name="mongoTemplate" ref="mongoTemplate" /> </bean> <bean id="mongoTemplate" class="org.springframework.data.mongodb.core.MongoTemplate"> <constructor-arg name="mongo" ref="mongo" /> <constructor-arg name="databaseName" value="nature" /> </bean> <!-- Factory bean that creates the Mongo instance --> <bean id="mongo" class="org.springframework.data.mongodb.core.MongoFactoryBean"> <property name="host" value="localhost" /> <property name="port" value="27017" /> </bean> <!-- Activate annotation configured components --> <context:annotation-config /> <!-- Scan components for annotations within the configured package --> <context:component-scan base-package="com.orangeslate.naturestore"> <context:exclude-filter type="annotation" expression="org.springframework.context.annotation.Configuration" /> </context:component-scan> </beans>
创建一个测试类。这里我已经创建了一个测试类,并通过ClassPathXmlApplicationContext来初始化他。
package com.orangeslate.naturestore.test; import org.springframework.context.ConfigurableApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; import com.orangeslate.naturestore.domain.Tree; import com.orangeslate.naturestore.repository.NatureRepositoryImpl; import com.orangeslate.naturestore.repository.Repository; public class MongoTest { public static void main(String[] args) { ConfigurableApplicationContext context = new ClassPathXmlApplicationContext( "classpath:/spring/applicationContext.xml"); Repository repository = context.getBean(NatureRepositoryImpl.class); // cleanup collection before insertion repository.dropCollection(); // create collection repository.createCollection(); repository.saveObject(new Tree("1", "Apple Tree", 10)); System.out.println("1. " + repository.getAllObjects()); repository.saveObject(new Tree("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. [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上下载到源码。
相关推荐
spring mongodb mongodb实例,spring data mongodb 操作实例总结
希望让更多喜欢mongodb的开发爱好者们加入这个阵营,共同学习,共同提高,这个示例简单易用,导入即上手,哥们我也是费了段时间整合这个最新稳定版本的,采用的是springmvc3.14+spring_data_mongodb1.3.2+mongodb_...
NULL 博文链接:https://lihao312.iteye.com/blog/2068046
使用Spring Data MongoDB和MongoDB 3.0 17.1.1。配置选项 17.1.2。WriteConcern和WriteConcernChecking 17.1.3。认证 17.1.4。服务器端验证 17.1.5。其他事情要注意 附录 附录A:命名空间参考 元素 附录B:Poppers...
Spring data mongodb实例 可以运行
spring Data家族给我们提供了一个现成的dao层框架,这里面有不同的项目,如Spring Data JPA, Spring Data Neo4j and Spring Data MongoDB,他们的共同特点是他们给我们提供了框架代码,不再需要我们自己去实现了。
- eclipselink:展示了如何在Spring Boot和Eclipselink中使用Spring Data JPA的示例项目。 - example:包含了各种示例包,展示了使用Spring Data JPA的不同级别。可以查看simple包以获取最基本的设置。 - ...
Spring Data MongoDB 的测试项目 在运行集成测试 (mvn verify) 之前。 确保您有一个在 localhost 上运行的 mongodb 实例。 它将使用本地主机上的测试数据库。 见 src/main/resources/application-test.properties
多租户春天mongodb 一个带有spring-data-mongodb支持多租户的项目 为什么?...这些集合中的数据结构是相同的,每个客户在一个mongodb实例中只是拥有自己的数据库。 关于此主题,在StackOverflow上有
1.包含对文档的基本增删改查(CRUD)的功能,基于Spring-data的MongoRepository扩展实现,update和insert操作本质上使用的同一个DAO接口,区别是update操作必须提供主键id,insert操作不提供id字段; 2.包含数据排序...
您使用一个MongoConverter配置YmerFactory ,该MongoConverter可以转换打算MongoDBFactory在MongoDB中的所有对象,并提供一个MongoDBFactory ,可以有效地定义应在哪个MongoDB实例中MongoDBFact
SpringBoot整合Mybatis,Maven,Mysql,swagger或spring data jpa或mongodb或springcloud;Spring Cloud Config分布式配置中心;Spring Cloud断路器Hystrix;Spring Cloud Feign中使用断路器;Spring Cloud路由网关...
该应用程序需要一个正在运行的MongoDB实例,最简单的启动方法是通过docker docker run --name some-mongo mongo 然后,您需要获取mongo容器的IP地址 docker inspect --format ' {{ .NetworkSettings.IPAddress }} ...
涵盖使用Spring Boot 进行Java EE 开发的绝大数应用场景,包含:Web 开发、数据访问、安全控制、批处理、异步消息、系统集成、开发与部署、应用监控、分布式系统开发等。 第一部分 点睛Spring 4.x 第1 章 Spring ...
涵盖使用Spring Boot 进行Java EE 开发的绝大数应用场景,包含:Web 开发、数据访问、安全控制、批处理、异步消息、系统集成、开发与部署、应用监控、分布式系统开发等。 第一部分 点睛Spring 4.x 第1 章 Spring ...
MongoDB实例的连接URI google.client.id 分配给应用程序的Google客户ID。 要获取更多详细信息,请访问 spring.mail.host 电子邮件服务器主机 spring.mail.port 电子邮件服务器端口 spring.mail.username 电子...
涵盖使用Spring Boot 进行Java EE 开发的绝大数应用场景,包含:Web 开发、数据访问、安全控制、批处理、异步消息、系统集成、开发与部署、应用监控、分布式系统开发等。 第一部分 点睛Spring 4.x 第1 章 Spring ...
网络编程实例 该项目包含在服务器端使用Java的Web应用程序的代码示例。技术清单这些示例涉及的主要技术是: Spring:Java框架。 这些示例基于Spring Boot,Spring MVC,Spring Data,Spring Security和Spring Test。...
AWS,MongoDB,Spring Framework,ETL 开发项目 项目源代码: 使用Bash开发了一个集群管理解决方案,以记录硬件规格并定期监视服务器集群中各个节点的资源使用情况.Docker使用Docker实例化RDBMS PostgreSQL数据库来...