Spring Boot CRUD using MongoDB
info
Create a Project, name it with mongo-blog, write a post API for mongo-blog, practice CRUD using MongoDB.
Spring Initializr
MongoDB 配置
创建新管理员用户
-- 切回 admin
use admin
db.createUser(
{
user: 'admin',
pwd: 'abc123456',
roles: [ { role: 'root', db: 'admin' } ]
}
);
Create new database and collection for CRUD
use mongoblog
db.createCollection("posts")
Maven 配置
在 pom.xml
中添加相关依赖
<!---mongodb相关依赖-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-mongodb</artifactId>
</dependency>
Spring Boot 配置文件
修改 application.yml
or application.properties
mongodb:
host: localhost # mongodb的连接地址
port: 27017 # mongodb的连接端口号
database: mall-port # mongodb的连接的数据库
MongoDB 的默认连接数据库是test
, 这里将权限切换到 admin
server.port = 8088
# mongoDB datasource
# change test -> admin
spring.data.mongodb.authentication-database = admin
spring.data.mongodb.database = mongoblog
spring.data.mongodb.port = 27017
spring.data.mongodb.host = localhost
spring.data.mongodb.username = admin
spring.data.mongodb.password = abc123456
Spring Boot CRUD
entity
package com.chuwa.mongoblog.entity;
// 指定使用的collection
@Document(collection = "posts")
public class Post {
// id主键设置Id 注解
@Id
private String id;
private String title;
private String description;
private String content;
private LocalDateTime createDateTime;
private LocalDateTime updateDateTime;
// 省略 getter和setter方法
}
dao
package com.chuwa.mongoblog.dao;
@Repository
public interface PostRepository extends MongoRepository<Post, String> {
}
payload
package com.chuwa.mongoblog.payload;
public class PostDto {
private String id;
private String title;
private String description;
private String content;
// 省略 getter和setter方法
}