企业级 SpringBoot 教程 (八)springboot整合mongodb

准备工作

  • 安装 MongoDB
  • jdk 1.8
  • maven 3.0
  • idea

环境依赖

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

<dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-mongodb</artifactId>
        </dependency>

数据源配置

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

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

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

spring.data.mongodb.uri=mongodb://name:[email protected]:27017/dbname

定义一个简单的实体

package com.forezp.entity;

import org.springframework.data.annotation.Id;

public class Customer {

    @Id
    public String id;

    public String firstName;
    public String lastName;

    public Customer() {}

    public Customer(String firstName, String lastName) {
        this.firstName = firstName;
        this.lastName = lastName;
    }

    @Override
    public String toString() {
        return String.format(
                "Customer[id=%s, firstName=‘%s‘, lastName=‘%s‘]",
                id, firstName, lastName);
    }

}

数据操作dao层

public interface CustomerRepository extends MongoRepository<Customer, String> {

    public Customer findByFirstName(String firstName);
    public List<Customer> findByLastName(String lastName);

}

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

测试

@SpringBootApplication
public class SpringbootMongodbApplication  implements CommandLineRunner {

    @Autowired
    private CustomerRepository repository;

    public static void main(String[] args) {
        SpringApplication.run(SpringbootMongodbApplication.class, args);
    }

    @Override
    public void run(String... args) throws Exception {
        repository.deleteAll();

        // save a couple of customers
        repository.save(new Customer("Alice", "Smith"));
        repository.save(new Customer("Bob", "Smith"));

        // fetch all customers
        System.out.println("Customers found with findAll():");
        System.out.println("-------------------------------");
        for (Customer customer : repository.findAll()) {
            System.out.println(customer);
        }
        System.out.println();

        // fetch an individual customer
        System.out.println("Customer found with findByFirstName(‘Alice‘):");
        System.out.println("--------------------------------");
        System.out.println(repository.findByFirstName("Alice"));

        System.out.println("Customers found with findByLastName(‘Smith‘):");
        System.out.println("--------------------------------");
        for (Customer customer : repository.findByLastName("Smith")) {
            System.out.println(customer);
        }
    }

完整的项目源码来源

原文地址:https://www.cnblogs.com/leafitit/p/9724102.html

时间: 2024-08-01 19:50:45

企业级 SpringBoot 教程 (八)springboot整合mongodb的相关文章

SpringBoot教程(3):整合Thymeleaf(中)

一.Thymeleaf 有哪些优点 1. Thymeleaf在有网络和无网络的环境下皆可运行,即它可以让美工在浏览器查看页面的静态效果,也可以让程序员在服务器查看带数据的动态页面效果.这是由于它支持 html 原型,然后在 html 标签里增加额外的属性来达到模板+数据的展示方式.浏览器解释 html 时会忽略未定义的标签属性,所以thymeleaf的模板可以静态地运行:当有数据返回到页面时,Thymeleaf 标签会动态地替换掉静态内容,使页面动态显示. 2.Thymeleaf 开箱即用的特性

Spring Boot2 系列教程 (十八) | 整合 MongoDB

微信公众号:一个优秀的废人.如有问题,请后台留言,反正我也不会听. 前言 如题,今天介绍下 SpringBoot 是如何整合 MongoDB 的. MongoDB 简介 MongoDB 是由 C++ 编写的非关系型数据库,是一个基于分布式文件存储的开源数据库系统,它将数据存储为一个文档,数据结构由键值 (key=>value) 对组成.MongoDB 文档类似于 JSON 对象.字段值可以包含其他文档,数组及文档数组,非常灵活.存储结构如下: { "studentId": &qu

springboot学习笔记-3 整合redis&amp;mongodb

一.整合redis 1.1 建立实体类 @Entity @Table(name="user") public class User implements Serializable { @Id @GeneratedValue(strategy=GenerationType.AUTO) private Long id; private String name; @DateTimeFormat(pattern="yyyy-MM-dd HH:mm:ss") private

Spring Boot2 系列教程 (九) | SpringBoot 整合 Mybatis

前言 如题,今天介绍 SpringBoot 与 Mybatis 的整合以及 Mybatis 的使用,本文通过注解的形式实现. 什么是 Mybatis MyBatis 是支持定制化 SQL.存储过程以及高级映射的优秀的持久层框架.MyBatis 避免了几乎所有的 JDBC 代码和手动设置参数以及获取结果集.MyBatis 可以对配置和原生 Map 使用简单的 XML 或注解,将接口和 Java 的 POJOs(Plain Old Java Objects,普通的 Java 对象)映射成数据库中的记

SpringBoot(二十六)整合Redis之共享Session

集群现在越来越常见,当我们项目搭建了集群,就会产生session共享问题.因为session是保存在服务器上面的.那么解决这一问题,大致有三个方案,1.通过nginx的负载均衡其中一种ip绑定来实现(通过ip绑定服务器其中一台,就没有集群概念了):2.通过cookie备份session实现(因为cookie数据保存在客户端,不推荐;3.通过redis备份session实现(推荐); 学习本章节之前,建议依次阅读以下文章,更好的串联全文内容,如已掌握以下列出知识点,请跳过: SpringBoot(

Springboot 2.0.4 整合Mybatis出现异常Property &#39;sqlSessionFactory&#39; or &#39;sqlSessionTemplate&#39; are required

在使用Springboot 2.0.4 整合Mybatis的时候出现异常Property 'sqlSessionFactory' or 'sqlSessionTemplate' are required,然后各种找日志百度,网上给了一种解决方法: 版本太高,使用手动注入sqlSessionFactory,然后用dao的实习类继承,因为我的项目没有dao 的实现类,直接是interface+mapper文件,所以直接忽略了,没有试过,想试一下可以试一下 阅读博客点这里(随手百度的):这里是传送门

elastic-job集成到springboot教程,和它的一个异常处理办法:Sharding item parameters &#39;1&#39; format error, should be int=xx,int=xx

先说这个Sharding item parameters '1' format error, should be int=xx,int=xx异常吧,这是在做动态添加调度任务的时候出现的,网上找了一会没有搜到任何信息,最后发现,是添加任务这个方法里有一个漏洞. 这个源码出自: 1 private ShardingItem parse(final String shardingItemParameter, final String originalShardingItemParameters) {

SpringBoot与PageHelper的整合示例详解

SpringBoot与PageHelper的整合示例详解 1.PageHelper简介 PageHelper官网地址: https://pagehelper.github.io/ 摘要: com.github.pagehelper.PageHelper是一款好用的开源免费的Mybatis第三方物理分页插件. PageHelper是一款好用的开源免费的Mybatis第三方物理分页插件,其实我并不想加上好用两个字,但是为了表扬插件作者开源免费的崇高精神,我毫不犹豫的加上了好用一词作为赞美. 原本以为

SpringBoot+SpringMVC+MyBatis快速整合搭建

使用过SpringBoot的同学都知道,SpringBoot的pom.xml中的坐标都是按功能导入的,jar包之间的依赖SpringBoot底层已经帮我们做好了,例如我们要整合SprngMVC,只需要导入SpringMVC的起步依赖就可以了,SpringBoot会帮我们导入Spring和SpringMVC整合需要的jar包. SpringBoot是基于Spring4.0设计的,不仅继承了Spring框架原有的优秀特性,而且还通过简化配置来进一步简化了Spring应用的整个搭建和开发过程.另外Sp

SpringBoot图文教程9—SpringBoot 导入导出 Excel 「Apache Poi」

摘自:https://www.cnblogs.com/bingyang-py/p/12407675.html 有天上飞的概念,就要有落地的实现 概念十遍不如代码一遍,朋友,希望你把文中所有的代码案例都敲一遍 先赞后看,养成习惯 SpringBoot 图文教程系列文章目录 SpringBoot图文教程1「概念+案例 思维导图」「基础篇上」 SpringBoot图文教程2—日志的使用「logback」「log4j」 SpringBoot图文教程3—「‘初恋’情结」集成Jsp SpringBoot图文