项目简介

项目地址

spring-boot-mongodb

项目依赖

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  3. xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
  4. <modelVersion>4.0.0</modelVersion>
  5. <parent>
  6. <groupId>org.springframework.boot</groupId>
  7. <artifactId>spring-boot-starter-parent</artifactId>
  8. <version>2.5.12</version>
  9. <relativePath/> <!-- lookup parent from repository -->
  10. </parent>
  11. <groupId>com.study</groupId>
  12. <artifactId>spring-boot-mongodb</artifactId>
  13. <version>0.0.1-SNAPSHOT</version>
  14. <name>spring-boot-mongodb</name>
  15. <description>spring-boot-mongodb</description>
  16. <properties>
  17. <java.version>1.8</java.version>
  18. </properties>
  19. <dependencies>
  20. <dependency>
  21. <groupId>org.springframework.boot</groupId>
  22. <artifactId>spring-boot-starter-data-mongodb</artifactId>
  23. </dependency>
  24. <dependency>
  25. <groupId>org.springframework.boot</groupId>
  26. <artifactId>spring-boot-starter-test</artifactId>
  27. <scope>test</scope>
  28. </dependency>
  29. </dependencies>
  30. <build>
  31. <plugins>
  32. <plugin>
  33. <groupId>org.springframework.boot</groupId>
  34. <artifactId>spring-boot-maven-plugin</artifactId>
  35. </plugin>
  36. </plugins>
  37. </build>
  38. </project>

文件配置

连接配置

mongodb连接配置如下:

  1. spring:
  2. data:
  3. mongodb:
  4. # uri: mongodb://admin:123456@localhost:27017/test_one_db?authSource=admin
  5. authentication-database: admin
  6. host: localhost
  7. port: 27017
  8. database: test_one_db
  9. username: admin
  10. password: '123456'

mongodb数据库与mysql不一样, mysql 一个普通用户可以管理多个数据库,但是mongo每一个库都有一个独立的管理用户,连接时需要输入对应用户密码

MongoDB监听配置

此类若不加,那么插入的一行会默认添加一个_class字段来存储实体类类型

不同的springboot版本的,其配置不一样,具体可百度

  1. package com.study.mongo.config;
  2. import org.springframework.beans.factory.annotation.Autowired;
  3. import org.springframework.context.ApplicationListener;
  4. import org.springframework.context.annotation.Configuration;
  5. import org.springframework.context.event.ContextRefreshedEvent;
  6. import org.springframework.data.mongodb.core.MongoTemplate;
  7. import org.springframework.data.mongodb.core.convert.DefaultMongoTypeMapper;
  8. import org.springframework.data.mongodb.core.convert.MappingMongoConverter;
  9. import org.springframework.data.mongodb.core.convert.MongoConverter;
  10. /**
  11. * @author lei
  12. * @version 1.0
  13. * @date 2020/02/16 11:22
  14. * @desc: 监听芒果 保存数据
  15. */
  16. @Configuration
  17. public class ApplicationReadyListener implements ApplicationListener<ContextRefreshedEvent> {
  18. private final MongoTemplate oneMongoTemplate;
  19. public ApplicationReadyListener(MongoTemplate oneMongoTemplate) {
  20. this.oneMongoTemplate = oneMongoTemplate;
  21. }
  22. private static final String TYPE_KEY = "_class";
  23. @Override
  24. public void onApplicationEvent(ContextRefreshedEvent contextRefreshedEvent) {
  25. MongoConverter converter = oneMongoTemplate.getConverter();
  26. if (converter.getTypeMapper().isTypeKey(TYPE_KEY)) {
  27. ((MappingMongoConverter) converter).setTypeMapper(new DefaultMongoTypeMapper(null));
  28. }
  29. }
  30. }

代码编写

实体类

  1. package com.study.mongo.domain;
  2. import lombok.Data;
  3. import org.springframework.data.annotation.Id;
  4. import org.springframework.data.mongodb.core.mapping.Document;
  5. import java.util.Date;
  6. /**
  7. * @author Leo
  8. * @version 1.0
  9. * @className UserInfoDO
  10. * @description TODO
  11. * @date 2022/4/16 17:35
  12. **/
  13. @Document("userInfo")
  14. @Data
  15. public class UserInfoDO {
  16. /** 自定义mongo主键 加此注解可自定义主键类型以及自定义自增规则
  17. * 若不加 插入数据数会默认生成 ObjectId 类型的_id 字段
  18. * org.springframework.data.annotation.Id 包下
  19. * mongo库主键字段还是为_id 。不必细究(本文实体类中为id)
  20. */
  21. @Id
  22. private String id;
  23. private String name;
  24. private String sex;
  25. private String city;
  26. private Date dateBirth;
  27. }

DAO层

  1. package com.study.mongo.repository;
  2. import com.study.mongo.domain.UserInfoDO;
  3. import org.springframework.data.mongodb.repository.MongoRepository;
  4. /**
  5. * @author Leo
  6. * @version 1.0
  7. * @className UserInfoRepository
  8. * @description TODO
  9. * @date 2022/4/16 17:38
  10. **/
  11. public interface UserInfoRepository extends MongoRepository<UserInfoDO, String> {
  12. }
  • 继承 org.springframework.data.mongodb.repository.MongoRepository 接口,第一个泛型设置对应的实体是 UserInfoDO ,第二个泛型设置对应的主键类型是 String。
  • 因为实现了 MongoRepository 接口,Spring Data MongoDB 会自动生成对应的 CRUD 等等的代码。😈 是不是很方便。
  • MongoRepository 类图如下:

image.png

简单测试

  1. package com.study.mongo;
  2. import com.study.mongo.domain.CommentDO;
  3. import com.study.mongo.domain.UserInfoDO;
  4. import com.study.mongo.repository.CommentRepository;
  5. import com.study.mongo.repository.UserInfoRepository;
  6. import org.junit.jupiter.api.Test;
  7. import org.junit.runner.RunWith;
  8. import org.slf4j.Logger;
  9. import org.slf4j.LoggerFactory;
  10. import org.springframework.beans.factory.annotation.Autowired;
  11. import org.springframework.boot.test.context.SpringBootTest;
  12. import org.springframework.test.context.junit4.SpringRunner;
  13. import java.util.Calendar;
  14. import java.util.Date;
  15. import java.util.List;
  16. @RunWith(SpringRunner.class)
  17. @SpringBootTest(classes = SpringBootMongodbApplication.class)
  18. class SpringBootMongodbApplicationTests {
  19. @Autowired
  20. private UserInfoRepository userInfoRepository;
  21. private final Logger log = LoggerFactory.getLogger(SpringBootMongodbApplicationTests.class);
  22. @Test
  23. void save() {
  24. UserInfoDO userInfoDO = new UserInfoDO();
  25. userInfoDO.setName("jjcc");
  26. userInfoDO.setSex("man");
  27. userInfoDO.setCity("长沙");
  28. userInfoDO.setDateBirth(new Date(97, Calendar.FEBRUARY, 2));
  29. UserInfoDO save = userInfoRepository.save(userInfoDO);
  30. }
  31. }

MongoRepository基于方法名查询

在 Spring Data 中,支持根据方法名作生成对应的查询(WHERE)条件,进一步进化我们使用 JPA ,具体是方法名以 findBy、existsBy、countBy、deleteBy 开头,后面跟具体的条件。具体的规则,在 《 《Spring Data JPA —— Query Creation》 文档中,已经详细提供。如下:

关键字 方法示例 JPQL snippet
And findByLastnameAndFirstname … where x.lastname = ?1 and x.firstname = ?2
Or findByLastnameOrFirstname … where x.lastname = ?1 or x.firstname = ?2
Is, Equals findByFirstname,findByFirstnameIs,findByFirstnameEquals … where x.firstname = ?1
Between findByStartDateBetween … where x.startDate between ?1 and ?2
LessThan findByAgeLessThan … where x.age < ?1
LessThanEqual findByAgeLessThanEqual … where x.age <= ?1
GreaterThan findByAgeGreaterThan … where x.age > ?1
GreaterThanEqual findByAgeGreaterThanEqual … where x.age >= ?1
After findByStartDateAfter … where x.startDate > ?1
Before findByStartDateBefore … where x.startDate < ?1
IsNull, Null findByAge(Is)Null … where x.age is null
IsNotNull, NotNull findByAge(Is)NotNull … where x.age not null
Like findByFirstnameLike … where x.firstname like ?1
NotLike findByFirstnameNotLike … where x.firstname not like ?1
StartingWith findByFirstnameStartingWith … where x.firstname like ?1 (parameter bound with appended %)
EndingWith findByFirstnameEndingWith … where x.firstname like ?1 (parameter bound with prepended %)
Containing findByFirstnameContaining … where x.firstname like ?1 (parameter bound wrapped in %)
OrderBy findByAgeOrderByLastnameDesc … where x.age = ?1 order by x.lastname desc
Not findByLastnameNot … where x.lastname <> ?1
In findByAgeIn(Collection ages) … where x.age in ?1
NotIn findByAgeNotIn(Collection ages) … where x.age not in ?1
True findByActiveTrue() … where x.active = true
False findByActiveFalse() … where x.active = false
IgnoreCase findByFirstnameIgnoreCase … where UPPER(x.firstame) = UPPER(?1)

MongoTemplate

在 Spring Data MongoDB 中,有一个 MongoTemplate 类,提供了 MongoDB 操作模板,方便我们操作 MongoDB 。

https://www.iocoder.cn/Spring-Boot/MongoDB/?self
https://blog.csdn.net/leilei1366615/article/details/104340891

多数据源配置,Aggregation管道使用 事务使用

https://blog.csdn.net/leilei1366615/article/details/104348504