之前有个项目,用的是Springboot框架,对接的数据库是mongodb,当时花了一些时间去做这个配置mongodb的连接,现在把这个过程记录下来,以免遗忘。
一,在pom中添加依赖。
& lt; !——增加mongodb支持,在
& lt; dependency>
& lt; groupId> org.springframework.boot
& lt; artifactId> spring-boot-starter-data-mongodb
& lt; version> 1.5.9.RELEASE
& lt;/dependency>
二,配置数据源
在项目中,使用的配置文件是yaml格式的,所以配置信息如下:
<代码>春: 数据: mongodb: uri: mongodb://地址代码>
如果使用的是属性格式的话,配置信息则是,
<代码> spring.data.mongodb。uri=mongodb://地址代码>
三,在实体中添加注解
在实体添加@Document注解,收集=岸杂Φ谋砻啊?br/>在属性上添加@Filed注解,值为对应的字段名。
<代码> @ getter @ setter @Document(收集=坝没А? 公开课用户{/* 用户名: */@Field (" id ") 私人字符串id;/* 用户名 */@Field(“用户”) 私人字符串的用户名;/* 性别 */@Field(“性”) 私人字符串性; }代码>
四,在业务层使用MongoDb的方法:
<代码> @ service 公共类UserServiceImpl实现UserService { @ 私人MongoTemplate MongoTemplate; @Override 公共长getCount () { 查询查询=new查询(); 长数=mongoTemplate.count(查询、User.class); 返回计数; } }代码>
五,MongoTemplate常使用的方法
<代码> 1。插入 “mongoTemplate.insert(对象),“ 2 .删除代码>
查询查询=新的查询(Criteria.where (“_id") . (id),
mongoTemplate.remove(查询,AutomaticAlarm.class);
<代码> 3。修改 ' ' ' 查询查询=new查询(Criteria.where (“_id”) . (id)); 更新更新=更新。更新(“要更新的字段”,“更新的值”); mongoTemplate。updateFirst(查询、更新Object.class); 代码>
-
<李>查询
1。查找所有李>
mongoTemplate.findAll (Object.class);
2。条件查询(具体某个字段的值)
查询查询=新的查询(Criteria.where(“字段1“).(“值1“));
mongoTemplate。找到(查询,Object.class);
3 .条件查询(大于小于)
标准标准=Criteria.where(“字段“).gte(某个值).lte(某个值),
查询查询=new查询(标准),
mongoTemplate。找到(查询,Object.class);
4。模糊查询
模式模式=Pattern.compile (“^ 。“+ searchKey +“。“美元);//这里时使用的是正则匹配,searchKey是关键字,接口传参,也可以自己定义。
标准标准=Criteria.where (“_id") .regex(模式),
mongoTemplate。找到(查询,Object.class);
5。分页查询
<代码>查询查询=new查询(); query.skip(“跳过的数据条数”).limit(“一页的数据条数”); mongoTemplate。找到(查询,Object.class); 代码>
6。聚合查询
聚合aggregation1=Aggregation.newAggregation (Aggregation.group (“sex") .count ()。as (“peopleCount"));//这里的聚合条件由自己定义
AggregationResults
<代码>六,增强配置 如果我们在项目中需要管理MongoDB的最大连接时长,套接字保持活跃,最大等待时长等,那么我们在pom文件中需要引入一个增强管理包。 & lt; !——增加mongoplus支持——比; & lt; dependency> & lt; groupId> com.spring4all & lt; artifactId> mongodb-plus-spring-boot-starter & lt; version> 1.0.0.RELEASE & lt;/dependency> 同时在项目启动类SpringBootMainApplication上添加一个注解@EnableMongoPlus。 我们就可以在配置文件中添加这些配置了。代码>春天
:
数据:
mongodb:
uri: mongodb://地址
选择:
socket-keep-alive:真正的
max-connection-idle-time: 60000
connect-timeout: 36000
min-connection-per-host: 5
threads-allowed-to-block-for-connection-multiplier: 5
最大等待时间:120000
socket-timeout: 0
max-connection-life-time: 0
heartbeat-socket-timeout: 36000
heartbeat-connect-timeout: 36000
min-heartbeat-frequency: 5
心跳频率:10