在SpringBoot中使用MongoDB的简单场景案例MongoDB 是一种非关系型数据库,也被称为 NoSQL 数据
MongoDB 是一种非关系型数据库,也被称为 NoSQL 数据库,它主要以文档的形式存储数据。这些文档的格式通常是 BSON(一种包含类型的 JSON 格式)。下面是 MongoDB 的一些核心原理:
-
文档模型:
- 在 MongoDB 中,数据被存储为文档,这些文档类似于 JSON 对象。每个文档都有一组键值对,值可以是各种数据类型(如字符串、数字、数组、文档等)。
- 文档可以容纳复杂的嵌套结构,这使得 MongoDB 在存储复杂和多层次的数据方面非常灵活。
-
集合:
- 文档被组织在集合中,集合类似于关系数据库中的表。不同的是,集合内的文档不需要有相同的结构,这种模式的灵活性是 MongoDB 的一个显著特点。
-
索引:
- 为了提高查询效率,MongoDB 支持对文档中的一个或多个字段建立索引。索引可以显著提高查询速度。
-
查询语言:
- MongoDB 提供了一个功能强大的查询语言,支持文档的各种查询操作,包括字段查找、范围查询、正则表达式搜索等。
- 查询可以返回完整的文档或者只是部分字段,还可以进行排序和分组。
-
复制和高可用性:
- MongoDB 支持数据的自动复制,提高数据的可用性和灾难恢复能力。通过复制集,数据可以在多个服务器之间复制,确保数据的安全性和高可用性。
- 在复制集中,可以有一个主节点和多个从节点,主节点处理所有写操作,从节点可以用于读操作以及在主节点故障时自动接管角色成为新的主节点。
-
分片:
- 对于大规模数据集,MongoDB 支持分片技术,即数据分布在多个服务器上,以便可以扩展数据库的存储容量和查询处理能力。
- 分片可以根据预定义的规则自动进行,使得数据管理更加高效。
简单场景案例
让我们来构建一个使用 Spring Boot 和 MongoDB 的简单博客系统。这个系统将允许用户创建、读取、更新和删除博客文章。我们将包括用户认证和授权的功能,以确保用户只能编辑和删除他们自己的文章。
技术栈
- Spring Boot: 用于创建 RESTful API。
- MongoDB: 作为后端数据库。
- Spring Data MongoDB: 提供 MongoDB 的集成和数据访问操作。
- Spring Security: 用于用户认证和授权。
项目结构
这个项目将包含以下几个主要部分:
- 模型 (
Post
,User
) - 仓库 (
PostRepository
,UserRepository
) - 服务 (
PostService
,UserService
) - 控制器 (
PostController
,UserController
) - 安全配置 (
SecurityConfig
)
步骤
1. 设置 Spring Boot 项目
首先,使用 Spring Initializr 创建一个新的 Spring Boot 项目。选择以下依赖:
- Spring Web
- Spring Data MongoDB
- Spring Security
2. 配置 MongoDB
在 application.properties
文件中配置 MongoDB 数据库连接:
spring.data.mongodb.uri=mongodb://localhost:27017/blog
3. 定义模型
// Post.java
package com.example.blog.model;
import org.springframework.data.annotation.Id;
import org.springframework.data.mongodb.core.mapping.Document;
import java.util.Date;
@Document
public class Post {
@Id
private String id;
private String title;
private String content;
private Date createdAt;
private String authorId;
// Getters and Setters
}
// User.java
package com.example.blog.model;
import org.springframework.data.annotation.Id;
import org.springframework.data.mongodb.core.mapping.Document;
@Document
public class User {
@Id
private String id;
private String username;
private String password;
private String role;
// Getters and Setters
}
4. 创建仓库
// PostRepository.java
package com.example.blog.repository;
import com.example.blog.model.Post;
import org.springframework.data.mongodb.repository.MongoRepository;
public interface PostRepository extends MongoRepository<Post, String> {
}
// UserRepository.java
package com.example.blog.repository;
import com.example.blog.model.User;
import org.springframework.data.mongodb.repository.MongoRepository;
public interface UserRepository extends MongoRepository<User, String> {
User findByUsername(String username);
}
5. 服务层
// PostService.java
package com.example.blog.service;
import com.example.blog.model.Post;
import com.example.blog.repository.PostRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
@Service
public class PostService {
@Autowired
private PostRepository postRepository;
public List<Post> getAllPosts() {
return postRepository.findAll();
}
public Post getPostById(String id) {
return postRepository.findById(id).orElse(null);
}
public Post createPost(Post post) {
post.setCreatedAt(new Date());
return postRepository.save(post);
}
public Post updatePost(String id, Post updatedPost) {
return postRepository.findById(id)
.map(post -> {
post.setTitle(updatedPost.getTitle());
post.setContent(updatedPost.getContent());
return postRepository.save(post);
}).orElse(null);
}
public void deletePost(String id) {
postRepository.deleteById(id);
}
}
// UserService.java
package com.example.blog.service;
import com.example.blog.model.User;
import com.example.blog.repository.UserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
@Service
public class UserService {
@Autowired
private UserRepository userRepository;
public User createUser(User user) {
return userRepository.save(user);
}
}
6. 控制器
// PostController.java
package com.example.blog.controller;
import com.example.blog.model.Post;
import com.example.blog.service.PostService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.util.List;
@RestController
@RequestMapping("/api/posts")
public class PostController {
@Autowired
private PostService postService;
@GetMapping
public List<Post> getAllPosts() {
return postService.getAllPosts();
}
@GetMapping("/{id}")
public Post getPostById(@PathVariable String id) {
return postService.getPostById(id);
}
@PostMapping
public Post createPost(@RequestBody Post post) {
return postService.createPost(post);
}
@PutMapping("/{id}")
public Post updatePost(@PathVariable String id, @RequestBody Post post) {
return postService.updatePost(id, post);
}
@DeleteMapping("/{id}")
public void deletePost(@PathVariable String id) {
postService.deletePost(id);
}
}
// UserController.java
package com.example.blog.controller;
import com.example.blog.model.User;
import com.example.blog.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
@RestController
@RequestMapping("/api/users")
public class UserController {
@Autowired
private UserService userService;
@PostMapping
public User createUser(@RequestBody User user) {
return userService.createUser(user);
}
}
7. 安全配置
// SecurityConfig.java
package com.example.blog.config;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.csrf().disable()
.authorizeRequests()
.antMatchers("/api/posts/**").authenticated()
.antMatchers("/api/users/**").permitAll()
.and()
.httpBasic();
}
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
PasswordEncoder encoder = new BCryptPasswordEncoder();
auth.inMemoryAuthentication()
.withUser("user").password(encoder.encode("password")).roles("USER")
.and()
.withUser("admin").password(encoder.encode("admin")).roles("ADMIN");
}
}
转载自:https://juejin.cn/post/7411406818025799690