Spring Boot 整合MongoDB

安装 Docker

https://www.cnblogs.com/zk2020/p/15547782.html

Docker安装MondoDB

# 拉去镜像
docker pull mongo:latest
# 创建和启动容器。-d 前台还是后台启动默认false,--restart=always 退出容器时总是重启,
# -p 指定容器暴露的端口号,--name指定容器的名字,-v 给容器挂在存储卷,挂载到容器的某个目录
docker run -d --restart=always -p 27017:27017 --name mongodb -v /data/mongodb:/data/db mongo
# 进入容器
docker exec -it mongodb /bin/bash
# 以 admin进入 mongodb
mongo admin
# 创建一个admin管理员账号
db.createUser({ user: 'root', pwd: 'root', roles: [ { role: "userAdminAnyDatabase", db: "admin" } ] });
# 退出mongodb
quit()

# 创建普通用户,密码
docker exec -it mongodb admin
db.auth("root","root");
db.createUser({ user: 'zs', pwd: '123456', roles: [ { role: "readWrite", db: "app" } ] });

Spring-Boot整合MongoDB

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-mongodb</artifactId>
</dependency>
# 应用名称
server.port=8081

# 这种方式不可行
#spring.data.mongodb.port=27017
#spring.data.mongodb.host=192.168.11.8
#spring.data.mongodb.username=root
#spring.data.mongodb.password=root

spring.data.mongodb.uri=mongodb://root:root@192.168.11.8:27017/test?authSource=admin&authMechanism=SCRAM-SHA-1
#                 格式: mongodb://[username:password@]host1[:port1][,host2[:port2],...[,hostN[:portN]]][/[database][?options]]

public interface StudentDao extends MongoRepository<Student, String> {

}
@NoArgsConstructor
@AllArgsConstructor
@Data
public class Student implements Serializable {
    static final long serialVersionUID = 1L;
    @Id// 必须指定id列
    private String studentId;

    private String studentName;

    private Integer studentAge;

    private Double studentScore;

    private Date studentBirthday;

//    private String teacherName;
}
@SpringBootTest
class MongodbApplicationTests {
    @Autowired
    StudentDao studentDao;

    @Test
    void contextLoads() {
        /*for (int i = 0; i < 10; i++) {
            studentDao.save(new Student((20 + i) + "", "TvT" + i, 15 + i, 88.0, new Date()));
        }*/
        //保存对象,如果id为空则随机
//        System.out.println(studentDao.save(new Student(null, "赵六", 30, 88.0, new Date())));

        //查询全部
//        System.out.println(studentDao.findAll());

        //查询数据库总数
//        System.out.println(studentDao.count());

        //查询姓名为张三的数量
        /*System.out.println(
                studentDao.count(
                        Example.of(
                                new Student(null, "张三", null, null, null)
                        )
                )
        );*/

        //查询姓名张三的用户
//        System.out.println(studentDao.findOne(Example.of(  new Student(null, "张三", null, null, null))));

        //根据id判断是否存在
//        System.out.println(studentDao.existsById("1"));
//        Student s = new Student();
//        s.setStudentId("0");
//        System.out.println(studentDao.exists(Example.of(s)));

        //排序查询按照id降序
//        System.out.println(studentDao.findAll(Sort.by(Sort.Order.asc("id"))));
        //排序查询,根据id默认升序
//        System.out.println(studentDao.findAll(Sort.by(Sort.Order.by("id"))));

        //分页查询
//        studentDao.findAll(PageRequest.of(0, 5)).stream().forEach(System.out::println);

        //批量查询
//        studentDao.findAllById(Arrays.asList("1", "2")).forEach(System.out::println);

        //更新,利用save更新所有字段都更新
//        Student s = new Student();
//        s.setStudentId("1");
//        s.setStudentName("吉良吉影");
//        studentDao.save(s);


        //添加一个新字段(先查询在保存 或者 直接保存一个新的对象)
//        Optional<Student> optional = studentDao.findById("1");
//        Student student = optional.get();
//        student.setTeacherName("张三");
//        studentDao.save(student);

        //删除全部
//        studentDao.deleteAll();
    }

}
posted @ 2022-11-01 16:53  MikiKawai  阅读(42)  评论(0编辑  收藏  举报