SpringBoot2.7.4整合MongoDb

目录

一、打开pom.xml添加依赖

二、更改resources配置名称为application.yml,增加配置参数

三、在study下面新建各种包名,编写相应的代码

四、编写启动类SpringbootStudyApplication

五、使用postman调试

六、下载地址


一、打开pom.xml添加依赖

XML 复制代码
<dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>

        <!-- Lombok(简化实体类) -->
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <optional>true</optional>
        </dependency>

        <!-- mongodb依赖-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-mongodb</artifactId>
        </dependency>

二、更改resources配置名称为application.yml,增加配置参数

XML 复制代码
server:
  port: 8888 #指定启动的端口
spring:
  data:
    mongodb:
      host: localhost # 连接地址
      port: 27017     # 端口号
      database: study # 数据库
      username: admin # 账号
      password: "123456" # 密码
      authentication-database: admin  # 认证库(可选,默认admin)

三、在study下面新建各种包名,编写相应的代码

1.entity层

java 复制代码
package com.saas.study.entity;

import com.fasterxml.jackson.annotation.JsonFormat;
import lombok.Data;
import org.springframework.data.annotation.Id;
import org.springframework.data.mongodb.core.mapping.Document;
import java.util.Date;

/**
 * 用户实体类
 */
@Data
@Document(collection = "user")
public class User {
    //主键,mongodb默认生成ObjectId
    @Id
    private String id;

    //姓名
    private String name;

    //年龄
    private Integer age;

    //电话
    private String phone;

    //创建时间,序列化时强制转换为东八区
    @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+8")
    private Date createTime;

}

2.config层

java 复制代码
package com.saas.study.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.mongodb.MongoDatabaseFactory;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.convert.DefaultDbRefResolver;
import org.springframework.data.mongodb.core.convert.DefaultMongoTypeMapper;
import org.springframework.data.mongodb.core.convert.MappingMongoConverter;
import org.springframework.data.mongodb.core.mapping.MongoMappingContext;


/**
 * mongodb配置类
 */
@Configuration
public class MongoConfig {

    @Bean
    public MongoTemplate mongoTemplate(MongoDatabaseFactory factory, MongoMappingContext context) {
        // 禁用 "_class" 字段(传入 null 表示不添加类型字段)
        DefaultMongoTypeMapper typeMapper = new DefaultMongoTypeMapper(null);
        MappingMongoConverter converter = new MappingMongoConverter(new DefaultDbRefResolver(factory), context);
        converter.setTypeMapper(typeMapper);

        return new MongoTemplate(factory, converter);
    }
}

3.controller层

java 复制代码
package com.saas.study.controller;

import com.saas.study.entity.User;
import com.saas.study.service.UserService;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;

/**
 * 用户控制层
 */
@RestController
@RequestMapping("/users")
public class UserController {
    @Resource
    private UserService userService;

    /**
     * 创建用户
     * @param user
     * @return
     */
    @PostMapping("/createUser")
    public User createUser(@RequestBody User user) {
        return userService.saveUser(user);
    }

    /**
     * 根据id获取单个用户
     * @param id
     * @return
     */
    @GetMapping("/getUser/{id}")
    public User getUser(@PathVariable("id") String id) {
        return userService.getUserById(id);
    }

    /**
     * 获取所有用户
     * @return
     */
    @GetMapping("/getAll")
    public List<User> getAll() {
        return userService.getAllUsers();
    }

    /**
     * 获取年龄大于指定的用户
     * @param age
     * @return
     */
    @GetMapping("/getUsersByAgeGreaterThan")
    public List<User> getUsersByAgeGreaterThan(@RequestParam(required = true) Integer age) {
        return userService.getUsersByAgeGreaterThan(age);
    }

    /**
     * 根据用户名称和手机号码查询
     * @param name
     * @param phone
     * @return
     */
    @GetMapping("/findByNameAndPhone")
    public User findByNameAndPhone(@RequestParam(required = true) String name,
                                         @RequestParam(required = true) String phone) {
        return userService.findByNameAndPhone(name,phone);
    }

    /**
     * 删除用户
     * @param id
     */
    @GetMapping("/deleteUser/{id}")
    public void deleteUser(@PathVariable("id") String id) {
        userService.deleteUser(id);
    }
}

4.service层

java 复制代码
package com.saas.study.service;

import com.saas.study.entity.User;

import java.util.List;

/**
 * 用户业务逻辑接口
 */
public interface UserService {
    User saveUser(User user);

    User getUserById(String id);

    List<User> getAllUsers();

    List<User> getUsersByAgeGreaterThan(Integer age);

    User findByNameAndPhone(String name, String phone);

    void deleteUser(String id);
}
java 复制代码
package com.saas.study.service.impl;

import com.saas.study.dao.UserRepository;
import com.saas.study.entity.User;
import com.saas.study.service.UserService;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import java.util.Date;
import java.util.List;

/**
 * 用户业务层实现类
 */
@Service
public class UserServiceImpl implements UserService {
    @Resource
    private UserRepository userRepository;

    /**
     * 添加用户信息
     * @param user
     * @return
     */
    @Override
    public User saveUser(User user) {
        user.setCreateTime(new Date());
        return userRepository.save(user);
    }

    /**
     * 根据用户id获取用户
     * @param id
     * @return
     */
    @Override
    public User getUserById(String id) {
        return userRepository.findById(id).orElse(null);
    }

    /**
     * 查询所有用户信息
     * @return
     */
    @Override
    public List<User> getAllUsers() {
        return userRepository.findAll();
    }

    /**
     * 查询大于指定岁数的用户
     * @param age
     * @return
     */
    @Override
    public List<User> getUsersByAgeGreaterThan(Integer age) {
        return userRepository.findByAgeGreaterThan(age);
    }

    /**
     * 根据用户名和电话号码查询指定用户
     * @param name
     * @param phone
     * @return
     */
    @Override
    public User findByNameAndPhone(String name, String phone) {
        return userRepository.findByNameAndPhone(name, phone);
    }

    /**
     * 删除用户
     * @param id
     */
    @Override
    public void deleteUser(String id) {
        userRepository.deleteById(id);
    }
}

5.dao层

java 复制代码
package com.saas.study.dao;

import com.saas.study.entity.User;
import org.springframework.data.mongodb.repository.MongoRepository;
import java.util.List;

/**
 * 操作数据库dao
 */
public interface UserRepository extends MongoRepository<User, String> {

    List<User> findByAgeGreaterThan(Integer age);

    User findByNameAndPhone(String name, String phone);
}

四、编写启动类SpringbootStudyApplication

java 复制代码
package com.saas.study;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class SpringbootStudyApplication {

    public static void main(String[] args) {
        SpringApplication.run(SpringbootStudyApplication.class, args);
    }

}

五、使用postman调试

1.访问http://localhost:8888/users/createUser

{

"name": "小明",

"age": 22,

"phone": "13800000000"

}

2.访问http://localhost:8888/users/getUser/692973f1fcf85b328ec9c16d

3.访问http://localhost:8888/users/getUsersByAgeGreaterThan?age=100

六、下载地址

1.百度云: https://pan.baidu.com/s/1LJ-wNNY00xOhxFaq2mpRHQ 提取码: q1ew

相关推荐
e***985732 分钟前
springboot接入deepseek深度求索 java
java·spring boot·后端
0***v77732 分钟前
redis批量删除namespace下的数据
数据库·redis·缓存
q***062933 分钟前
【细如狗】记录一次使用MySQL的Binlog进行数据回滚的完整流程
android·数据库·mysql
8***848234 分钟前
SQL 实战—递归 SQL:层级结构查询与处理树形数据
java·数据库·sql
小马爱打代码34 分钟前
k8s:SpringBoot应用容器化
spring boot·容器·kubernetes
睡前要喝豆奶粉37 分钟前
EF Core动态sql
数据库·sql·c#·.netcore
f***241139 分钟前
SpringBoot中整合ONLYOFFICE在线编辑
java·spring boot·后端
p***s9139 分钟前
mysql用户名怎么看
数据库·mysql
5***g22941 分钟前
Ubuntu 系统下安装 Nginx
数据库·nginx·ubuntu