java

关注公众号 jb51net

关闭
首页 > 软件编程 > java > SpringBoot使用MongoDB

在SpringBoot中使用MongoDB的简单场景案例

作者:一只爱撸猫的程序猿

MongoDB 是一种非关系型数据库,也被称为 NoSQL 数据库,它主要以文档的形式存储数据,本文给大家介绍了在SpringBoot中使用MongoDB的简单场景案例,并通过代码示例讲解的非常详细,需要的朋友可以参考下

MongoDB 是一种非关系型数据库,也被称为 NoSQL 数据库,它主要以文档的形式存储数据。这些文档的格式通常是 BSON(一种包含类型的 JSON 格式)。下面是 MongoDB 的一些核心原理:

简单场景案例

让我们来构建一个使用 Spring Boot 和 MongoDB 的简单博客系统。这个系统将允许用户创建、读取、更新和删除博客文章。我们将包括用户认证和授权的功能,以确保用户只能编辑和删除他们自己的文章。

技术栈

项目结构

这个项目将包含以下几个主要部分:

步骤

1. 设置 Spring Boot 项目

首先,使用 Spring Initializr 创建一个新的 Spring Boot 项目。选择以下依赖:

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");
    }
}

以上就是在SpringBoot中使用MongoDB的简单场景案例的详细内容,更多关于SpringBoot使用MongoDB的资料请关注脚本之家其它相关文章!

您可能感兴趣的文章:
阅读全文