本文讲解Spring Boot基础下,如何使用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>

数据源

方案一 使用 Spring Boot 默认配置

MongoDB 使用,在 Spring Boot 中同样提供了自配置功能。

默认使用localhost:27017的名称叫做test的数据库。

此外,我们也可以在 src/main/resources/application.properties 中配置数据源信息。

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

如果存在密码,配置改成如下

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

方案二 手动创建

通过 Java Config 创建mongoTemplate。

  1. @Configuration
  2. @EnableMongoRepositories
  3. public class MongoConfig extends AbstractMongoConfiguration {
  4. private String mongoHost = "localhost";
  5. private int mongoPort = 27017;
  6. private String dbName = "springboot-db";
  7. private static final String MONGO_BASE_PACKAGE = "com.lianggzone.springboot.action.data.mongodb.entity";
  8. @Autowired
  9. private ApplicationContext appContext;
  10. @Override
  11. protected String getDatabaseName() {
  12. return dbName;
  13. }
  14. @Override
  15. public Mongo mongo() throws Exception {
  16. MongoClient mongoClient = new MongoClient(mongoHost, mongoPort);
  17. return mongoClient;
  18. }
  19. @Override
  20. protected String getMappingBasePackage() {
  21. return MONGO_BASE_PACKAGE;
  22. }
  23. @Override
  24. @Bean
  25. public MongoTemplate mongoTemplate() throws Exception {
  26. return new MongoTemplate(mongo(), getDatabaseName());
  27. }
  28. }

使用mongoTemplate操作

实体对象

  1. @Document(collection = "author")
  2. public class Author {
  3. @Id
  4. private Long id;
  5. private String realName;
  6. private String nickName;
  7. // SET和GET方法
  8. }

DAO相关

我们通过mongoTemplate进行数据访问操作。

  1. @Repository
  2. public class AuthorDao {
  3. @Autowired
  4. private MongoTemplate mongoTemplate;
  5. public void add(Author author) {
  6. this.mongoTemplate.insert(author);
  7. }
  8. public void update(Author author) {
  9. this.mongoTemplate.save(author);
  10. }
  11. public void delete(Long id) {
  12. Query query = new Query();
  13. query.addCriteria(Criteria.where("_id").is(id));
  14. this.mongoTemplate.remove(query, Author.class);
  15. }
  16. public Author findAuthor(Long id) {
  17. return this.mongoTemplate.findById(id, Author.class);
  18. }
  19. public List<Author> findAuthorList() {
  20. Query query = new Query();
  21. return this.mongoTemplate.find(query, Author.class);
  22. }
  23. }

Service相关

Service层调用Dao层的方法,这个是典型的套路。

  1. @Service
  2. public class AuthorService {
  3. @Autowired
  4. private AuthorDao authorDao;
  5. public void add(Author author) {
  6. this.authorDao.add(author);
  7. }
  8. public void update(Author author) {
  9. this.authorDao.update(author);
  10. }
  11. public void delete(Long id) {
  12. this.authorDao.delete(id);
  13. }
  14. public Author findAuthor(Long id) {
  15. return this.authorDao.findAuthor(id);
  16. }
  17. public List<Author> findAuthorList() {
  18. return this.authorDao.findAuthorList();
  19. }
  20. }

Controller相关

为了展现效果,我们先定义一组简单的 RESTful API 接口进行测试。

  1. @RestController
  2. @RequestMapping(value="/data/mongodb/author")
  3. public class AuthorController {
  4. @Autowired
  5. private AuthorService authorService;
  6. /**
  7. * 查询用户列表
  8. */
  9. @RequestMapping(method = RequestMethod.GET)
  10. public Map<String,Object> getAuthorList(HttpServletRequest request) {
  11. List<Author> authorList = this.authorService.findAuthorList();
  12. Map<String,Object> param = new HashMap<String,Object>();
  13. param.put("total", authorList.size());
  14. param.put("rows", authorList);
  15. return param;
  16. }
  17. /**
  18. * 查询用户信息
  19. */
  20. @RequestMapping(value = "/{userId:\\d+}", method = RequestMethod.GET)
  21. public Author getAuthor(@PathVariable Long userId, HttpServletRequest request) {
  22. Author author = this.authorService.findAuthor(userId);
  23. if(author == null){
  24. throw new RuntimeException("查询错误");
  25. }
  26. return author;
  27. }
  28. /**
  29. * 新增方法
  30. */
  31. @RequestMapping(method = RequestMethod.POST)
  32. public void add(@RequestBody JSONObject jsonObject) {
  33. String userId = jsonObject.getString("user_id");
  34. String realName = jsonObject.getString("real_name");
  35. String nickName = jsonObject.getString("nick_name");
  36. Author author = new Author();
  37. if (author!=null) {
  38. author.setId(Long.valueOf(userId));
  39. }
  40. author.setRealName(realName);
  41. author.setNickName(nickName);
  42. try{
  43. this.authorService.add(author);
  44. }catch(Exception e){
  45. e.printStackTrace();
  46. throw new RuntimeException("新增错误");
  47. }
  48. }
  49. /**
  50. * 更新方法
  51. */
  52. @RequestMapping(value = "/{userId:\\d+}", method = RequestMethod.PUT)
  53. public void update(@PathVariable Long userId, @RequestBody JSONObject jsonObject) {
  54. Author author = this.authorService.findAuthor(userId);
  55. String realName = jsonObject.getString("real_name");
  56. String nickName = jsonObject.getString("nick_name");
  57. author.setRealName(realName);
  58. author.setNickName(nickName);
  59. try{
  60. this.authorService.update(author);
  61. }catch(Exception e){
  62. e.printStackTrace();
  63. throw new RuntimeException("更新错误");
  64. }
  65. }
  66. /**
  67. * 删除方法
  68. */
  69. @RequestMapping(value = "/{userId:\\d+}", method = RequestMethod.DELETE)
  70. public void delete(@PathVariable Long userId) {
  71. try{
  72. this.authorService.delete(userId);
  73. }catch(Exception e){
  74. throw new RuntimeException("删除错误");
  75. }
  76. }
  77. }

总结

上面这个简单的案例,让我们看到了 Spring Boot 整合 MongoDB 的整个流程。实际上,与 Spring 4 中 通过 Spring Data MongoDB 整合 MongoDB 是相同的, Spring Boot 默认集成了一些配置信息,但是个人更加偏向于方案二的手动创建方式,有更好的扩展性。

源代码

相关示例完整代码: springboot-action

(完)

如果觉得我的文章对你有帮助,请随意打赏。

Spring Boot 揭秘与实战(二) 数据存储篇 - MongoDB的更多相关文章

  1. Spring Boot 揭秘与实战(二) 数据存储篇 - 声明式事务管理

    文章目录 1. 声明式事务 2. Spring Boot默认集成事务 3. 实战演练4. 源代码 3.1. 实体对象 3.2. DAO 相关 3.3. Service 相关 3.4. 测试,测试 本文 ...

  2. Spring Boot 揭秘与实战(二) 数据存储篇 - ElasticSearch

    文章目录 1. 版本须知 2. 环境依赖 3. 数据源 3.1. 方案一 使用 Spring Boot 默认配置 3.2. 方案二 手动创建 4. 业务操作5. 总结 4.1. 实体对象 4.2. D ...

  3. Spring Boot 揭秘与实战(二) 数据存储篇 - Redis

    文章目录 1. 环境依赖 2. 数据源 2.1. 方案一 使用 Spring Boot 默认配置 2.2. 方案二 手动创建 3. 使用 redisTemplate 操作4. 总结 3.1. 工具类 ...

  4. Spring Boot 揭秘与实战(二) 数据存储篇 - JPA整合

    文章目录 1. 环境依赖 2. 数据源 3. 脚本初始化 4. JPA 整合方案一 通过继承 JpaRepository 接口 4.1. 实体对象 4.2. DAO相关 4.3. Service相关 ...

  5. Spring Boot 揭秘与实战(二) 数据存储篇 - MyBatis整合

    文章目录 1. 环境依赖 2. 数据源3. 脚本初始化 2.1. 方案一 使用 Spring Boot 默认配置 2.2. 方案二 手动创建 4. MyBatis整合5. 总结 4.1. 方案一 通过 ...

  6. Spring Boot 揭秘与实战(二) 数据存储篇 - 数据访问与多数据源配置

    文章目录 1. 环境依赖 2. 数据源 3. 单元测试 4. 源代码 在某些场景下,我们可能会在一个应用中需要依赖和访问多个数据源,例如针对于 MySQL 的分库场景.因此,我们需要配置多个数据源. ...

  7. Spring Boot 揭秘与实战(二) 数据存储篇 - MySQL

    文章目录 1. 环境依赖 2. 数据源3. 脚本初始化 2.1. 方案一 使用 Spring Boot 默认配置 2.2. 方案二 手动创建 4. 使用JdbcTemplate操作5. 总结 4.1. ...

  8. Spring Boot 揭秘与实战(二) 数据缓存篇 - 快速入门

    文章目录 1. 声明式缓存 2. Spring Boot默认集成CacheManager 3. 默认的 ConcurrenMapCacheManager 4. 实战演练5. 扩展阅读 4.1. Mav ...

  9. Spring Boot 揭秘与实战(二) 数据缓存篇 - Redis Cache

    文章目录 1. Redis Cache 集成 2. 源代码 本文,讲解 Spring Boot 如何集成 Redis Cache,实现缓存. 在阅读「Spring Boot 揭秘与实战(二) 数据缓存 ...

随机推荐

  1. udp用户数据报协议

    UDP 是User Datagram Protocol的简称, 中文名是用户数据报协议,是OSI(Open System Interconnection,开放式系统互联) 参考模型中一种无连接的传输层 ...

  2. Oracle 11.2.0.4.0 Dataguard部署和日常维护(6)-Active Dataguard篇

    1. 检查主备库的状态 on primary column DATABASE_ROLE format a20 column OPEN_MODE format a15 column PROTECTION ...

  3. [luogu P2324] [SCOI2005]骑士精神

    [luogu P2324] [SCOI2005]骑士精神 题目描述 输入输出格式 输入格式: 第一行有一个正整数T(T<=10),表示一共有N组数据.接下来有T个5×5的矩阵,0表示白色骑士,1 ...

  4. python3+paramiko实现ssh客户端

    一.程序说明 ssh客户端实现主要有以下四个问题: 第一个问题是在python中ssh客户端使用哪个包实现----我们这里使用的是paramiko 第二个问题是怎么连接服务器----连接服务器直接使用 ...

  5. free结果解释

    free用于查询内存使用情况,不过其多个数值经常让人感到迷惑,下边对其结果各值进行解释. Mem 1862--总内存/1770--已使用内存/92--未使用内存/199--输出缓存/637--输入缓存 ...

  6. hashlib 库

    hashlib 库 hash 是一种算法,用来接收一系列数据,经过计算后得到一个hash值 hash值的三大特征: 1. 如果传入的数据一样,得到的hash值一样 2. 只要采用的hash算法固定,无 ...

  7. vue 添加vux

    1.命令添加vux npm install vux --save 2.在build/webpack.base.conf.js中配置 const vuxLoader = require('vux-loa ...

  8. The type java.lang.Object cannot be resolved

    有时候在Eclipse中打开或者导入项目时会出现标题字样的问题:The type java.lang.Object cannot be resolved. It is indirectly refer ...

  9. I/O复用(select)——回声服务器端/客户端

    一.select 使用select函数可以将多个文件描述符集中到一起统一监视,监视事件如下: 是否存在待读取数据. 是否可传输无阻塞传输数据. 是否发生异常. 将关心上述3种事件的文件描述发分别注册到 ...

  10. 转 举例说明使用MATLAB Coder从MATLAB生成C/C++代码步骤

    MATLAB Coder可以从MATLAB代码生成独立的.可读性强.可移植的C/C++代码. http://www.mathworks.cn/products/matlab-coder/ 使用MATL ...