项目简介
项目地址
项目依赖
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.5.12</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.study</groupId>
<artifactId>spring-boot-mongodb</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>spring-boot-mongodb</name>
<description>spring-boot-mongodb</description>
<properties>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-mongodb</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
文件配置
连接配置
mongodb连接配置如下:
spring:
data:
mongodb:
# uri: mongodb://admin:123456@localhost:27017/test_one_db?authSource=admin
authentication-database: admin
host: localhost
port: 27017
database: test_one_db
username: admin
password: '123456'
mongodb数据库与mysql不一样, mysql 一个普通用户可以管理多个数据库,但是mongo每一个库都有一个独立的管理用户,连接时需要输入对应用户密码
MongoDB监听配置
此类若不加,那么插入的一行会默认添加一个_class字段来存储实体类类型
不同的springboot版本的,其配置不一样,具体可百度
package com.study.mongo.config;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationListener;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.convert.DefaultMongoTypeMapper;
import org.springframework.data.mongodb.core.convert.MappingMongoConverter;
import org.springframework.data.mongodb.core.convert.MongoConverter;
/**
* @author lei
* @version 1.0
* @date 2020/02/16 11:22
* @desc: 监听芒果 保存数据
*/
@Configuration
public class ApplicationReadyListener implements ApplicationListener<ContextRefreshedEvent> {
private final MongoTemplate oneMongoTemplate;
public ApplicationReadyListener(MongoTemplate oneMongoTemplate) {
this.oneMongoTemplate = oneMongoTemplate;
}
private static final String TYPE_KEY = "_class";
@Override
public void onApplicationEvent(ContextRefreshedEvent contextRefreshedEvent) {
MongoConverter converter = oneMongoTemplate.getConverter();
if (converter.getTypeMapper().isTypeKey(TYPE_KEY)) {
((MappingMongoConverter) converter).setTypeMapper(new DefaultMongoTypeMapper(null));
}
}
}
代码编写
实体类
package com.study.mongo.domain;
import lombok.Data;
import org.springframework.data.annotation.Id;
import org.springframework.data.mongodb.core.mapping.Document;
import java.util.Date;
/**
* @author Leo
* @version 1.0
* @className UserInfoDO
* @description TODO
* @date 2022/4/16 17:35
**/
@Document("userInfo")
@Data
public class UserInfoDO {
/** 自定义mongo主键 加此注解可自定义主键类型以及自定义自增规则
* 若不加 插入数据数会默认生成 ObjectId 类型的_id 字段
* org.springframework.data.annotation.Id 包下
* mongo库主键字段还是为_id 。不必细究(本文实体类中为id)
*/
@Id
private String id;
private String name;
private String sex;
private String city;
private Date dateBirth;
}
DAO层
package com.study.mongo.repository;
import com.study.mongo.domain.UserInfoDO;
import org.springframework.data.mongodb.repository.MongoRepository;
/**
* @author Leo
* @version 1.0
* @className UserInfoRepository
* @description TODO
* @date 2022/4/16 17:38
**/
public interface UserInfoRepository extends MongoRepository<UserInfoDO, String> {
}
- 继承 org.springframework.data.mongodb.repository.MongoRepository 接口,第一个泛型设置对应的实体是 UserInfoDO ,第二个泛型设置对应的主键类型是 String。
- 因为实现了 MongoRepository 接口,Spring Data MongoDB 会自动生成对应的 CRUD 等等的代码。😈 是不是很方便。
- MongoRepository 类图如下:
简单测试
package com.study.mongo;
import com.study.mongo.domain.CommentDO;
import com.study.mongo.domain.UserInfoDO;
import com.study.mongo.repository.CommentRepository;
import com.study.mongo.repository.UserInfoRepository;
import org.junit.jupiter.api.Test;
import org.junit.runner.RunWith;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
@RunWith(SpringRunner.class)
@SpringBootTest(classes = SpringBootMongodbApplication.class)
class SpringBootMongodbApplicationTests {
@Autowired
private UserInfoRepository userInfoRepository;
private final Logger log = LoggerFactory.getLogger(SpringBootMongodbApplicationTests.class);
@Test
void save() {
UserInfoDO userInfoDO = new UserInfoDO();
userInfoDO.setName("jjcc");
userInfoDO.setSex("man");
userInfoDO.setCity("长沙");
userInfoDO.setDateBirth(new Date(97, Calendar.FEBRUARY, 2));
UserInfoDO save = userInfoRepository.save(userInfoDO);
}
}
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