源码位置
工程:https://gitee.com/MyFirstMyYun/spring-boot-project-case
项目源码:https://gitee.com/MyFirstMyYun/spring-boot-project-case/tree/master/mongdb-demo
整合步骤
1.引入pom依赖
<!--mongodb-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-mongodb</artifactId>
</dependency>
<!-- https://mvnrepository.com/artifact/org.mongodb/mongo-java-driver -->
<dependency>
<groupId>org.mongodb</groupId>
<artifactId>mongo-java-driver</artifactId>
<version>3.12.7</version>
</dependency>
2.application.properties配置信息如下
spring.data.mongodb.host=127.0.0.1
spring.data.mongodb.port=27017
spring.data.mongodb.username=cms
spring.data.mongodb.password=cms
spring.data.mongodb.database=example
如果打算在一行写:
1、有用户名和密码的情况
spring.data.mongodb.uri=mongodb://name:pass@localhost:27017/test,其中name是用户名,pass是密码。
2、没有用户名和密码的情况
spring.data.mongodb.uri=mongodb://localhost:27017/test。
3.POJO层
4.DAO层
5.Service层
6.Test类
7.如果报错
出现上述的错误,大概率是你的mongdb的“cms”用户不具备对“example”数据库的操作权限。 那么,如何验证我们的猜想呢?
第一步:
第二步:
这样,我们就把cms用户与example数据库关联起来了。重新启动Test测试类试试吧!
7.结果
成功运行之后,发现mongdb中新【创建】了数据库、新【插入】了数据。
但是查看索引的时候,发现索引没有被建立:
use example;
db.email_message.getIndexes(); // 查询结果为空
8.解决@CompoundIndex复合索引注解不生效问题
spring boot + spring data MongoDB 项目中使用@CompoundIndex注解来生成MongoDB索引,但是项目启动后未生效
解决方案:
在配置文件中增加:spring.data.mongodb.auto-index-creation: true
注意:该注解在第一次生成表的时候生效,如果表已经存在,需要删除表重新生成。故该策略适用于新建表时使用。