SpringBoot V2.7.5整合MongoDB V6.0.0图文详解

2 篇文章 0 订阅
1 篇文章 0 订阅


该文档适用于MongoDB数据库结合Java实际项目,适合刚接触的同学们尽快接触并上手开发
在学习新的知识时,请一定要放松心情,切勿被出现的错误和耽误的时间扰乱思绪,多看源码;紧张时请与心爱的人聊聊天,转换思路;网上查不到的写法请在源码中寻找答案,版本不同差别较大!

一. Windows10安装MongoDB

安装教程地址:Windows10安装MongoDB图文详解

二. 使用IDE创建SpringBoot项目

例,使用idea创建项目时,可直接在nosql选项中选择添加MongoDB;生成SpringBoot项目后,pom.xml文件自带spring-boot-starter-data-mongodb。

三. 总体目录结构

总体目录结构

四. 创建config配置类

在这里插入图片描述

@Configuration
public class MongoConfiguration {

    @Resource
    private MongoDatabaseFactorySupport mongoDatabaseFactorySupport;
    @Resource
    private MappingMongoConverter mappingMongoConverter;

    @Bean
    public MongoTemplate mongoTemplate() {

        mappingMongoConverter.setTypeMapper(new DefaultMongoTypeMapper(null));
        MongoTemplate mongoTemplate = new MongoTemplate(mongoDatabaseFactorySupport, mappingMongoConverter);
        return mongoTemplate;
    }
}

重写MongoTemplate,并使用@Bean注解注入到程序中,在具体使用CRUD方法时,在该类中引用MongoTemplate。

五. 新增entity实体类

在这里插入图片描述

@Data
@AllArgsConstructor
@NoArgsConstructor
@Document(collection = "vibration_realtime_data") //指定文档名(表名)
public class VibrationRealTimeData {

    @Field(value = "tag_name")
    private String tagName;

    @Field(value = "real_time")
    private String realTime;

}

1.一定要写上@Document(collection = "文档名/表名")注解,代表该类是MongoDB数据库的某个文档(表)的实体类;collection代表具体的文档名/表名"。
2.在字段名称上添加@Field(value = "tag_name")注解,代表该属性对应文档(表)的某个字段;value代表具体的字段名称。

六. 在SpringBoot项目中MongoDB数据库的连接方式

1.没有在数据库中设置账户密码的连接方式
在这里插入图片描述

spring:
  data:
    mongodb:
      uri: mongodb://127.0.0.1:27017/online_spotcheck?appName=MongoDB+Compass&directConnection=true&serverSelectionTimeoutMS=2000

mongodb://IP:端口号/数据库名称,问号后边的美容根据实际情况,可写可不写。

七. 代码中写insert方法

SpringBootTest测试代码示例:
在这里插入图片描述

@Test
  void insertDataTest(){
      SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
      VibrationRealTimeData vibrationRealTimeData = new VibrationRealTimeData();
      vibrationRealTimeData.setTagName("TG_TEST1");
      vibrationRealTimeData.setRealTime(simpleDateFormat.format(new Date()));
      mongoTemplate.insert(vibrationRealTimeData,"vibration_realtime_data");
  }

1.insert方法使用实体类和表名称两个参数的方法,源码如下否则会出现代码不会报错,但数据不能插入到文档名(表)中,必须要有相对应的文档名/表名。
在这里插入图片描述

/*
	 * (non-Javadoc)
	 * @see org.springframework.data.mongodb.core.MongoOperations#insert(java.lang.Object, java.lang.String)
	 */
	@Override
	@SuppressWarnings("unchecked")
	public <T> T insert(T objectToSave, String collectionName) {

		Assert.notNull(objectToSave, "ObjectToSave must not be null!");
		Assert.notNull(collectionName, "CollectionName must not be null!");

		ensureNotIterable(objectToSave);
		return (T) doInsert(collectionName, objectToSave, this.mongoConverter);
	}

2.数据插入成功后 查看MongoDB对应的文档名/表,会显示
在这里插入图片描述
注:id在没有自定义的情况下,由数据库系统自创自增。

八. 代码中写query方法

SpringBootTest测试代码示例:
在这里插入图片描述

@Test
   void queryDataTest(){
       VibrationRealTimeData vibrationRealTimeData = new VibrationRealTimeData();
       vibrationRealTimeData.setTagName("TG_TEST1");
       Query query = new Query(Criteria.where("tag_name").is(vibrationRealTimeData.getTagName()));
       System.out.println(mongoTemplate.find(query, VibrationRealTimeData.class,"vibration_realtime_data"));
   }

1.query引包import org.springframework.data.mongodb.core.query.Query;先确定查询的方式,生成查询条件;例如,本次使用文档/表中的“tag_name”字段,确定字段值,使用find方法查询数据。
2.find方法要使用带查询条件,实体类,文档/表名三个参数的方法,源码如下;
在这里插入图片描述

@Override
   public <T> List<T> find(Query query, Class<T> entityClass, String collectionName) {

   	Assert.notNull(query, "Query must not be null!");
   	Assert.notNull(collectionName, "CollectionName must not be null!");
   	Assert.notNull(entityClass, "EntityClass must not be null!");

   	return doFind(collectionName, query.getQueryObject(), query.getFieldsObject(), entityClass,
   			new QueryCursorPreparer(query, entityClass));
   }

3.查询成功后,会显示全部数据
在这里插入图片描述
注:当查询字段值重复时使用findOne方法(参数同find),系统也不会报错,MongoDB数据库会自动返回插入时间最早的数据。

九. 代码中写remove方法

SpringBootTest测试代码示例:
在这里插入图片描述

@Test
   void deleteDataTest(){
       VibrationRealTimeData vibrationRealTimeData = new VibrationRealTimeData();
       vibrationRealTimeData.setTagName("TG_TEST1");
       Query query = new Query(Criteria.where("tag_name").is(vibrationRealTimeData.getTagName()));
       // remove 方法会将全部相同地查询主键数据全部删除 所以请保证查询字段数据的唯一性 防止误删除
       mongoTemplate.remove(query,VibrationRealTimeData.class,"vibration_realtime_data");
   }

1.remove方法的写与find方法大致相同,先确定查询的主字段;
2.使用三个参数的remove方法;
注:remove 方法会将全部相同地查询主键数据全部删除 所以请保证查询字段数据的唯一性 防止误删除。

十. 遇到并解决的问题

1. 在查询中系统出现报错Query failed with error code 2 with name 'BadValue' and error message 'Field 'locale' is invalid in: { locale: "vibration_realtime_data" }' on server 127.0.0.1:27017; nested exception is com.mongodb.MongoQueryException: Query failed with error code 2 with的主要原因
答:需要注意实体类中的注解
在这里插入图片描述
该注解中"collection"和” collation”是两个功能不同的注解,一定要注意;源码如下:

在这里插入图片描述

The collection the document representing the entity is supposed to be stored in. If not configured, a default collection name will be derived from the type's name. The attribute supports SpEL expressions to dynamically calculate the collection to based on a per operation basis.
Returns:
the name of the collection to be used.
翻译:表示实体的文档应该存储在其中的集合中。如果未配置,则从类型的名称派生默认集合名称。该属性支持SpEL表达式,以根据每个操作的基础动态计算集合。
返回:
要使用的集合的名称。

在这里插入图片描述

Defines the collation to apply when executing a query or creating indexes.
Returns:
an empty String by default.
Since:
2.2
翻译:定义在执行查询或创建索引时应用的排序规则。
返回:
默认为空字符串。
自:
22

欢迎大家加入CSDN开发云
CSDN开发云

  • 2
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 4
    评论
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值