首页 > 数据库 >Spring Boot中使用MongoDB数据库

Spring Boot中使用MongoDB数据库

时间:2023-08-08 12:37:34浏览次数:49  
标签:String MongoDB Boot springframework mongodb Spring org import public


本章我们来学习Spring Boot中使用MongoDB数据库,有两种使用方式,一是直接使用mongotemplate,二是新建实体相关的repository接口。

引入依赖

在pom.xml中加入spring-boot-starter-data-mongodb引入对mongodb的访问支持依赖,它的实现依赖spring-data-mongodb。

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

最终pom.xml如下:

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>com.biologic</groupId>
  <artifactId>23mofang-biologic</artifactId>
  <version>0.0.1-SNAPSHOT</version>
  
  
   <!-- 编译版本为JDK 1.8 -->
    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
        <java.version>1.8</java.version>
    </properties>

    <!-- Spring Boot 核心jar包 -->
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>1.5.3.RELEASE</version>
    </parent>
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>  
        <groupId>org.springframework.boot</groupId>  
        <artifactId>spring-boot-starter-data-mongodb</artifactId>  
    </dependency>  
    </dependencies>
    
    <build>  
  <plugins>  
    <plugin>  
        <groupId>org.springframework.boot</groupId>  
        <artifactId>spring-boot-maven-plugin</artifactId>  
    </plugin>  
  </plugins>  
 </build>  
  
</project>

数据源的配置

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

spring.data.mongodb.uri=mongodb://localhost:27017/mydb

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

spring.data.mongodb.uri=mongodb://zzq:123456@localhost:27017/mydb

如果多个节点集群配置

#more ip cluster  
#spring.data.mongodb.uri=mongodb://user:pwd@ip1:port1,ip2:port2/database

新建实体

package com.biologic.entity;

@Document(collection = "user")
public class User {

	 @Id
    private String id;
    @Field("username")
	private String username;
	private String password;
	private String registerTime;
	private String phone;
	private String name;
	private String sex;
	private String age;

	public String getId() {
		return id;
	}

	public void setId(String id) {
		this.id = id;
	}

	public String getUsername() {
		return username;
	}

	public void setUsername(String username) {
		this.username = username;
	}

	public String getPassword() {
		return password;
	}

	public void setPassword(String password) {
		this.password = password;
	}

	public String getRegisterTime() {
		return registerTime;
	}

	public void setRegisterTime(String registerTime) {
		this.registerTime = registerTime;
	}

	public String getPhone() {
		return phone;
	}

	public void setPhone(String phone) {
		this.phone = phone;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public String getSex() {
		return sex;
	}

	public void setSex(String sex) {
		this.sex = sex;
	}

	public String getAge() {
		return age;
	}

	public void setAge(String age) {
		this.age = age;
	}

}

方式一直接使用mongotemplate

springboot会自动注入mongotemplate,使用引用

@Autowired
	MongoTemplate mongotemplate;

即可。如下:

package com.biologic.api;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
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.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.biologic.entity.User;

@Controller
@EnableAutoConfiguration
public class SampleController {

	@Autowired
	MongoTemplate mongotemplate;

	@RequestMapping("/")
	@ResponseBody
	String home() {
		Query query = new Query();
		query.addCriteria(Criteria.where("name").is("酒仙"));
		String name = mongotemplate.findOne(query, User.class).getName();
		return name;
	}

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

}

方式二新建实体相关的repository接口

新建定义repository接口继承mongoRepository接口

package com.biologic.api.service;

import org.springframework.data.mongodb.repository.MongoRepository;
import org.springframework.stereotype.Service;

import com.biologic.entity.User;


@Service
public interface UserRepository extends MongoRepository<User, String> {  
    
   public User findByName(String name); 

}

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

repository接口需要在启动程序的同级目录或者子目录中,例如结构如下:

Spring Boot中使用MongoDB数据库_User

使用方式如下:

package com.biologic.api;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.biologic.api.service.UserRepository;



@Controller
@EnableAutoConfiguration
public class SampleController {

	@Autowired
	UserRepository userRepository;

	@RequestMapping("/")
	@ResponseBody
	String home() {
		String name = userRepository.findByName("酒仙").getName();
		return name;
	}

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

}

可能遇到的问题

Description:

Field userRepository in com.biologic.api.SampleController required a bean of type 'com.biologic.service.UserRepository' that could not be found.


Action:

Consider defining a bean of type 'com.biologic.service.UserRepository' in your configuration.

原因

SpringBoot项目的Bean装配默认规则是根据Application类所在的包位置从上往下扫描!
“Application类”是指SpringBoot项目入口类。这个类的位置很关键:

如果Application类所在的包为:com.biologic.api,则只会扫描com.biologic.api包及其所有子包,如果service或dao所在包不在com.biologic.api及其子包下,则不会被扫描!

根据英文的提示是在配置中找不到一个指定自动注入类型的bean,经过多方排查得出结论:
正常情况下加上@Component注解的类会自动被Spring扫描到生成Bean注册到spring容器中,既然说没找到,也就是该注解被没有被spring识别,问题的核心关键就在application类的注解SpringBootApplication上。

解决方式

至此,得出两种解决办法:

  1 .将接口与对应的实现类放在与application启动类的同一个目录或者他的子目录下,这样注解可以被扫描到,这是最省事的办法

注意这样也是扫描不到的

Spring Boot中使用MongoDB数据库_MongoDB_02


这样是可以的

Spring Boot中使用MongoDB数据库_mongodb_03

2,如果是其他子项目引入进来的包,可以通过对Application类添加@ComponentScan(basePackages={“xxx.xxx”,”xxx.xxx”})来指定扫描的包,但是需要注意的是引入的包路径仍然需要跟application启动类的同一个目录或者他的子目录下。而且一旦指定后就不会在默认扫描Application类下的包,所以需要扫描Application类下的包需要把Application类下的包也加在路径里。在指定的application类上加上扫描路径这么一行注解,手动指定application类要扫描哪些包下的注解,如下:

@ComponentScan(basePackages = {"com.biologic.api","com.biologic.service"})


标签:String,MongoDB,Boot,springframework,mongodb,Spring,org,import,public
From: https://blog.51cto.com/u_16218512/7007066

相关文章

  • Spring Boot返回Json
    我们在前面的接口示例中是直接返回的字符串如下:但是我们有时候是需要返回json对象的。SpringBoot封装了JSON解析包Jackson的功能,只需要直接返回一个实体即可实现json的格式。如下:新建实体Sex.javapackagecom.biologic.entity;publicclassSex{privateStringsex;......
  • SpringBoot配置文件和修改端口
    我们在上一篇文章中已经运行起了一个简单的基础项目并运行起来了。SpringBoot简介项目创建和运行使用但是我们发现简单版的SpringBoot项目没有配置文件,定制版的项目有一个配置文件application.properties,我们还可以发现有些SpringBoot的项目使用的是xml或者yml配置文件。那么......
  • Bootstrap框架----多条记录双文本(List)添加
    有时候我们需要实现双文本的多条记录录入,传给后台保存成List的结构。界面交互设计如图:可动态添加行数,每行固定两个文本录入。我们在之前的文章中已经在SpringMVC基础框架的基础上应用了BootStrap的后台框架,在此基础上记录多条文本录入用法。应用bootstrap模板基础项目源码下载......
  • 分布式链路跟踪springcloud-Sleuth和springcloud-Zipkin
    分布式链路跟踪springcloud-Sleuth和springcloud-Zipkin前言各大厂分布式链路跟踪系统架构对比随着互联网架构的扩张,分布式系统变得日趋复杂,越来越多的组件开始走向分布式化,如微服务、消息收发、分布式数据库、分布式缓存、分布式对象存储、跨域调用,这些组件共同构成了繁杂的分......
  • Java后端07(Spring未完成)
    Spring​ 涉及的设计模式:单例模式,简单工厂模式,代理模式,观察者模式,反射,注解。。。。。Spring配置文件文件头<?xmlversion="1.0"encoding="UTF-8"?><beansxmlns="http://www.springframework.org/schema/beans"xmlns:context="http://www.springframework......
  • kettle案例一抽取gz格式文本内容保存到mongodb
    版本和启动我们这里使用的7.1版本,官网下载的安装包为pdi-ce-7.1.0.0-12.zip。安装目录下非常多的执行程序,但没有明显的启动图标。Kettle常用三大家族:Spoon、Pan、Kitchen。Spoon:通过图形界面方式设计、运行、调试Job与Transformation。Pan:通过脚本命令方式来运行Transform......
  • Bootstrap框架----新建示例--各种input
    我们在之前的文章中已经在SpringMVC基础框架的基础上应用了BootStrap的后台框架,在此基础上记录新建示例。应用bootstrap模板基础项目源码下载地址为:SpringMVC+Shiro+MongoDB+BootStrap基础框架我们在基础项目中已经做好了首页index的访问。现在就在index.jsp页面和index的路由Con......
  • Bootstrap框架----弹出层录入
    我们经常需要在不跳转页面的情况下新增录入的交互。本章记录弹出层录入的交互方式。效果如图:我们在之前的文章中已经在SpringMVC基础框架的基础上应用了BootStrap的后台框架,在此基础上记录check选择。应用bootstrap模板基础项目源码下载地址为:SpringMVC+Shiro+MongoDB+BootSt......
  • c#操作mongodb防止重复插入
    原理:把可以唯一标识的字段提出来放在字符串列中,当字符串不包含要插入的数据时再进行数据操作MongoClientclient;MongoServerserver;MongoDatabasedatabase;client=newMongoClient("mongodb://192.168.0.4");serv......
  • 遇到的问题-----c#操作mongodb用foreach遍历集合报错curcor not found
    foreach(varttdocindatabase.GetCollection("集合名").FindAll()){}执行了一部分就报错curcornotfound了 原因是curcor有一定的时限如果数据太多的话可考虑分几部分来处理vardata=database.GetCollection("集合名");......