转载请标明出处:

原文首发于:https://www.fangzhipeng.com/springboot/2017/07/11/springboot8-mongodb/

本文出自方志朋的博客

这篇文章主要介绍springboot如何整合mongodb。

准备工作

环境依赖

在pom文件引入spring-boot-starter-data-mongodb依赖:

  1. <dependency>
  2. <groupId>org.springframework.boot</groupId>
  3. <artifactId>spring-boot-starter-data-mongodb</artifactId>
  4. </dependency>

##数据源配置

如果mongodb端口是默认端口,并且没有设置密码,可不配置,sprinboot会开启默认的。

  1. spring.data.mongodb.uri=mongodb://localhost:27017/springboot-db

mongodb设置了密码,这样配置:

  1. spring.data.mongodb.uri=mongodb://name:pass@localhost:27017/dbname

定义一个简单的实体

mongodb


  1. package com.forezp.entity;
  2. import org.springframework.data.annotation.Id;
  3. public class Customer {
  4. @Id
  5. public String id;
  6. public String firstName;
  7. public String lastName;
  8. public Customer() {}
  9. public Customer(String firstName, String lastName) {
  10. this.firstName = firstName;
  11. this.lastName = lastName;
  12. }
  13. @Override
  14. public String toString() {
  15. return String.format(
  16. "Customer[id=%s, firstName='%s', lastName='%s']",
  17. id, firstName, lastName);
  18. }
  19. }

数据操作dao层

  1. public interface CustomerRepository extends MongoRepository<Customer, String> {
  2. public Customer findByFirstName(String firstName);
  3. public List<Customer> findByLastName(String lastName);
  4. }

写一个接口,继承MongoRepository,这个接口有了几本的CURD的功能。如果你想自定义一些查询,比如根据firstName来查询,获取根据lastName来查询,只需要定义一个方法即可。注意firstName严格按照存入的mongodb的字段对应。在典型的java的应用程序,写这样一个接口的方法,需要自己实现,但是在springboot中,你只需要按照格式写一个接口名和对应的参数就可以了,因为springboot已经帮你实现了。

测试

  1. @SpringBootApplication
  2. public class SpringbootMongodbApplication implements CommandLineRunner {
  3. @Autowired
  4. private CustomerRepository repository;
  5. public static void main(String[] args) {
  6. SpringApplication.run(SpringbootMongodbApplication.class, args);
  7. }
  8. @Override
  9. public void run(String... args) throws Exception {
  10. repository.deleteAll();
  11. // save a couple of customers
  12. repository.save(new Customer("Alice", "Smith"));
  13. repository.save(new Customer("Bob", "Smith"));
  14. // fetch all customers
  15. System.out.println("Customers found with findAll():");
  16. System.out.println("-------------------------------");
  17. for (Customer customer : repository.findAll()) {
  18. System.out.println(customer);
  19. }
  20. System.out.println();
  21. // fetch an individual customer
  22. System.out.println("Customer found with findByFirstName('Alice'):");
  23. System.out.println("--------------------------------");
  24. System.out.println(repository.findByFirstName("Alice"));
  25. System.out.println("Customers found with findByLastName('Smith'):");
  26. System.out.println("--------------------------------");
  27. for (Customer customer : repository.findByLastName("Smith")) {
  28. System.out.println(customer);
  29. }
  30. }

在springboot的应用程序,加入测试代码。启动程序,控制台打印了:

Customers found with findAll():

-------------------------------

Customer[id=58f880f589ffb696b8a6077e, firstName=‘Alice’, lastName=‘Smith’]

Customer[id=58f880f589ffb696b8a6077f, firstName=‘Bob’, lastName=‘Smith’]

Customer found with findByFirstName(‘Alice’):

--------------------------------

Customer[id=58f880f589ffb696b8a6077e, firstName=‘Alice’, lastName=‘Smith’]

Customers found with findByLastName(‘Smith’):

--------------------------------

Customer[id=58f880f589ffb696b8a6077e, firstName=‘Alice’, lastName=‘Smith’]

Customer[id=58f880f589ffb696b8a6077f, firstName=‘Bob’, lastName=‘Smith’]

测试通过。

源码下载:https://github.com/forezp/SpringBootLearning

参考资料

accessing-data-mongodb




扫码关注公众号有惊喜

(转载本站文章请注明作者和出处 方志朋的博客

SpringBoot非官方教程 | 第八篇:springboot整合mongodb的更多相关文章

  1. SpringBoot进阶教程 | 第四篇:整合Mybatis实现多数据源

    这篇文章主要介绍,通过Spring Boot整合Mybatis后如何实现在一个工程中实现多数据源.同时可实现读写分离. 准备工作 环境: windows jdk 8 maven 3.0 IDEA 创建 ...

  2. (转)SpringBoot非官方教程 | 第七篇:springboot开启声明式事务

    springboot开启事务很简单,只需要一个注解@Transactional 就可以了.因为在springboot中已经默认对jpa.jdbc.mybatis开启了事事务,引入它们依赖的时候,事物就 ...

  3. SpringBoot非官方教程 | 第二十三篇: 异步方法

    转载请标明出处: 原文首发于https://www.fangzhipeng.com/springboot/2017/07/11/springboot-ansy/ 本文出自方志朋的博客 这篇文章主要介绍 ...

  4. (转)SpringBoot非官方教程 | 第三篇:SpringBoot用JdbcTemplates访问Mysql

    本文介绍springboot通过jdbc访问关系型MySQL,通过spring的JdbcTemplate去访问. 准备工作 jdk 1.8 maven 3.0 idea mysql 初始化mysql: ...

  5. SpringBoot非官方教程 | 第六篇:springboot整合mybatis

    转载请标明出处: 原文首发于:https://www.fangzhipeng.com/springboot/2017/07/11/springboot-mybatis/ 本文出自方志朋的博客 本文主要 ...

  6. SpringBoot非官方教程 | 第五篇:springboot整合 beatlsql

    转载请标明出处: 原文首发于:https://www.fangzhipeng.com/springboot/2017/07/11/springboot5-beatlsql/ 本文出自方志朋的博客 Be ...

  7. SpringBoot非官方教程 | 第四篇:SpringBoot 整合JPA

    转载请标明出处: 原文首发于:https://www.fangzhipeng.com/springboot/2017/07/11/springboot4-jpaJ/ 本文出自方志朋的博客 JPA全称J ...

  8. SpringBoot非官方教程 | 第七篇:springboot开启声明式事务

    转载请标明出处: http://blog.csdn.net/forezp/article/details/70833629 本文出自方志朋的博客 springboot开启事务很简单,只需要一个注解@T ...

  9. SpringBoot非官方教程 | 第二十篇: 处理表单提交

    转载请标明出处: 原文首发于:https://www.fangzhipeng.com/springboot/2017/07/11/springboot-form/ 本文出自方志朋的博客 这篇文件主要介 ...

随机推荐

  1. 【Linux】快速清空当前文件

    $ : > filename $ > filename $ echo "" > filename $ echo > filename $ cat /dev/ ...

  2. 深入理解JavaScript系列(3):全面解析Module模式

    简介 Module模式是JavaScript编程中一个非常通用的模式,一般情况下,大家都知道基本用法,本文尝试着给大家更多该模式的高级使用方式. 首先我们来看看Module模式的基本特征: 模块化,可 ...

  3. Linux.net && mono

    资料: http://www.cnblogs.com/xiaodiejinghong/archive/2013/04/01/2994216.html http://www.cnblogs.com/sh ...

  4. js之可迭代对象

    遍历Array可以采用下标循环,遍历Map和Set就无法使用下标.为了统一集合类型,ES6标准引入了新的iterable类型,Array.Map和Set都属于iterable类型. 具有iterabl ...

  5. Jquery系列:checkbox 获取值、选中、设置值、事件监听等操作

    <div id="divId" class="divTable"> <div class="tableBody"> ...

  6. Java NIO(三) Buffer

    Java NIO中的Buffer用于和NIO通道进行交互.如你所知,数据是从通道读入缓冲区,从缓冲区写入到通道中的. 缓冲区本质上是一块可以写入数据,然后可以从中读取数据的内存.这块内存被包装成NIO ...

  7. Android 自定义倾斜字体

    public class RotateTextView extends AppCompatTextView { private static final int DEFAULT_DEGREES = 0 ...

  8. 通过describe命令学习Kubernetes的pod属性详解

    我们可以首先使用kubectl get pods命令得到pod列表,比如我们想研究pod nginx-storage-pod的明细: 使用命令kubectl describe pod nginx-st ...

  9. 为什么使用中间件下载时总是收到警告消息Object is in status Wait

    在使用中间件从ERP下载对象时,正常情况下应该看到如下提示消息: 然而有时遇到的是黄色的警告消息:Object is in status Wait. 如何自己排错呢?在函数SMOF0_INIT_DNL ...

  10. ABAP的权限检查跟踪(Authorization trace)工具

    事务码 STAUTHTRACE 1. 点击"Activate Trace" button激活跟踪: 可以看到跟踪状态已经处于打开状态. 在同一个application server ...