SpringBoot 2.1.7 集成 Spring Data MongoDB
使用SpringBoot集成 Spring Data MongoDB有两种方式,本文使用IDEA搭建:
- 1.Spring Initializr
- 2.使用IDEA插件
环境信息:
OS:Win10
Jdk:JavaSE 8
Ide:Idea Ultimate
Spring Boot:2.1.7.RELEASE
2.创建Web项目
Idea集成了Spring Initializr,新建项目:
- 1.选择Spring Initializr

-
2.填写基本信息

-
3.选择需要的工具
选择Web和Spring Data MongoDB等必要依赖:

- 4.确认完成
忽略我的其他项目:

3.创建数据库&表
3.1 创建数据库
手动或命令创建数据库studentService:

3.2 创建数据表
右键数据库,打开Open Shell执行Js脚本:
- 1.创建表
var names = db.getCollectionNames();
// -- Create Collections --
if (!names.includes('students')) {
db.createCollection("students", {
});
print("create collection students");
}
if (!names.includes('scores')) {
db.createCollection("scores", {
});
print("create collection scores");
}

- 2.创建表索引
// -- Create students indexes --
var studentsIndexNames = db.userRoles.getIndexes().map(function (i) {
return i.name
});
if (!studentsIndexNames.includes('unique_name_address')) {
db.students.createIndex({
"name": 1,
"address": 1
}, {
name: "unique_name_address",
background: true,
unique: true
});
print('create students index unique_name_address');
}
// -- Create scores indexes --
var scoresIndexNames = db.scores.getIndexes().map(function (i) {
return i.name
});
if (!scoresIndexNames.includes('unique_studentId_subject')) {
db.scores.createIndex({
"studentId": 1,
"subject": 1
}, {
name: "unique_studentId_subject",
background: true,
unique: true
});
print('create scores index unique_studentId_subject');
}

3.3 插入初始化数据
var studentsResult = db.students.findOne({
"name": "Even"});
if (studentsResult == null) {
db.students.insert([ /* 1 */
{
"name" : "Even",
"age" : 9.0,
"sex" : "Male",
"address" : "Xian",
"hobbies" : [
"YuWen",
"English"
]
},
/* 2 */
{
"name" : "Weison",
"age" : 10.0,
"sex" : "Male",
"address" : "Henan",
"hobbies" : [
"Wuli",
"English"
]
},
/* 3 */
{
"name" : "Angule",
"age" : 13

本文介绍了如何在SpringBoot 2.1.7项目中集成Spring Data MongoDB,包括创建Web项目、配置MongoDB连接、定义Domain、创建Repository、Service和Controller。详细步骤和代码参考链接提供。
最低0.47元/天 解锁文章
2036

被折叠的 条评论
为什么被折叠?



