目录
前言-与正文无关
生活远不止眼前的苦劳与奔波,它还充满了无数值得我们去体验和珍惜的美好事物。在这个快节奏的世界中,我们往往容易陷入工作的漩涡,忘记了停下脚步,感受周围的世界。让我们一起提醒自己,要适时放慢脚步,欣赏生活中的每一道风景,享受与家人朋友的温馨时光,发现那些平凡日子里隐藏的幸福时刻。因为,这些点点滴滴汇聚起来的,才是构成我们丰富多彩生活的本质。希望每个人都能在繁忙的生活中找到自己的快乐之源,不仅仅为了生存而工作,更为了更好的生活而生活.
送你张美图!希望你开心!
mongoClient和MongoTemplate
二者区别
Springboot 操作 MongoDB 有两种方式。
第一种方式是采用 Springboot 官方推荐的 JPA 方式,这种操作方式,使用简单但是灵活性比较差。也就是MongoClient
第二种方式是采用 Spring Data MongoDB 基于 MongoDB 官方 Java API 封装的 MongoTemplate 操作类对 MongoDB 进行操作,这种方式非常灵活,能满足绝大部分需求。也就是MongoTemplate
本文将采用第二种方式进行介绍!
MongoClient
MongoClient
是 MongoDB 官方 Java 驱动库提供的类。可以理解为是mysql的Jdbc框架,它直接与 MongoDB 服务器进行通信,负责建立连接、发送查询和命令以及接收响应。使用 MongoClient
通常涉及到编写比较底层的代码。你需要自己管理连接、编写查询语句、处理结果集等。它提供了与 MongoDB 交互的最大灵活性,允许你执行几乎所有类型的数据库操作,包括那些 Spring Data MongoDB 可能尚未提供支持的操作。
MongoTemplate
定义:MongoTemplate
是 Spring Data MongoDB 提供的一个高级抽象,它封装了 MongoClient
,提供了一个更高层次的模板方法 API 来简化 MongoDB 的操作。可以理解为是mysql的Mybatis框架。MongoTemplate
提供了相对简单的方法来执行查询、更新、删除等操作,同时集成了 Spring 的转换和异常处理机制。使用 MongoTemplate
,你不需要关心低层次的数据库连接和错误处理。
代码实践
配置
SpringBoot 工程依赖和配置
<!-- 引入springboot -->
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.1.0.RELEASE</version>
</parent>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-mongodb</artifactId>
</dependency>
添加配置文件
在application.properties文件中添加mongodb相关配置!
#配置数据库连接地址
spring.data.mongodb.uri=mongodb://userName:password@127.0.0.1:27017/dbName
userName:表示用户名,根据实际情况填写即可
password:表示用户密码,根据实际情况填写即可
dbName:表示数据库,可以自定义,初始化数据的时候,会自动创建
准备代码
创建实体类
创建一个实体类Person,其中注解@Document(collection="persons")表示当前实体类对应的集合名称是persons,类似于关系型数据库中的表名称。
注解@Id表示当前字段,在集合结构中属于主键类型。
/**
* 使用@Document注解指定集合名称
*/
@Document(collection="persons")
public class Person implements Serializable {
private static final long serialVersionUID = -3258839839160856613L;
/**
* 使用@Id注解指定MongoDB中的 _id 主键
*/
@Id
private Long id;
private String userName;
private String passWord;
private Integer age;
private Date createTime;
//...get/set
@Override
public String toString() {
return "Person{" +
"id=" + id +
", userName='" + userName + '\'' +
", passWord='" + passWord + '\'' +
", age=" + age +
", createTime=" + createTime +
'}';
}
}
新增
插入文档
MongoTemplate提供了insert()方法,用于插入文档,示例代码如下:
-
用于插入文档
没指定集合名称时,会取 @Document注解中的集合名称
@RunWith(SpringRunner.class)
@SpringBootTest
public class PersonServiceTest {
@Autowired
private MongoTemplate mongoTemplate;
/**
* 插入文档
* @throws Exception
*/
@Test
public void insert() throws Exception {
Person person =new Person();
person.setId(1l);
person.setUserName("张三");
person.setPassWord("123456");
person.setCreateTime(new Date());
mongoTemplate.insert(person);
}
}
-
自定义集合名称,插入文档
@RunWith(SpringRunner.class)
@SpringBootTest
public class PersonServiceTest {
@Autowired
private MongoTemplate mongoTemplate;
/**
* 自定义集合,插入文档
* @throws Exception
*/
@Test
public void insertCustomCollection() throws Exception {
Person person =new Person();
person.setId(1l);
person.setUserName("张三");
person.setPassWord("123456");
person.setCreateTime(new Date());
mongoTemplate.insert(person, "custom_person");
}
}
-
自定义集合,批量插入文档
如果采用批量插入文档,必须指定集合名称
@RunWith(SpringRunner.class)
@SpringBootTest
public class PersonServiceTest {
@Autowired
private MongoTemplate mongoTemplate;
/**
* 自定义集合,批量插入文档
* @throws Exception
*/
@Test
public void insertBatch() throws Exception {
List<Person> personList = new ArrayList<>();
Person person1 =new Person();
person1.setId(10l);
person1.setUserName("张三");
person1.setPassWord("123456");
person1.setCreateTime(new Date());
personList.add(person1);
Person person2 =new Person();
person2.setId(11l);
person2.setUserName("李四");
person2.setPassWord("123456");
person2.setCreateTime(new Date());
personList.add(person2);
mongoTemplate.insert(personList, "custom_person");
}
}
存储文档
MongoTemplate提供了save()方法,用于存储文档。
在存储文档的时候会通过主键 ID 进行判断,如果存在就更新,否则就插入,示例代码如下:
-
存储文档,如果没有插入,否则通过主键ID更新
@RunWith(SpringRunner.class)
@SpringBootTest
public class PersonServiceTest {
@Autowired
private MongoTemplate mongoTemplate;
/**
* 存储文档,如果没有插入,否则更新
* @throws Exception
*/
@Test
public void save() throws Exception {
Person person =new Person();
person.setId(13l);
person.setUserName("八八");
person.setPassWord("123456");
person.setAge(40);
person.setCreateTime(new Date());
mongoTemplate.save(person);
}
}
-
自定义集合,存储文档
@RunWith(SpringRunner.class)
@SpringBootTest
public class PersonServiceTest {
@Autowired
private MongoTemplate mongoTemplate;
/**
* 自定义集合,存储文档
* @throws Exception
*/
@Test
public void saveCustomCollection() throws Exception {
Person person =new Person();
person.setId(1l);
person.setUserName("张三");
person.setPassWord("123456");
person.setCreateTime(new Date());
mongoTemplate.save(person, "custom_person");
}
}
更新
MongoTemplate提供了updateFirst()和updateMulti()方法,用于更新文档,示例代码如下:
-
更新文档,匹配查询到的文档数据中的第一条数据
@RunWith(SpringRunner.class)
@SpringBootTest
public class PersonServiceTest {
@Autowired
private MongoTemplate mongoTemplate;
/**
* 更新文档,匹配查询到的文档数据中的第一条数据
* @throws Exception
*/
@Test
public void updateFirst() throws Exception {
//更新对象
Person person =new Person();
person.setId(1l);
person.setUserName("张三123");
person.setPassWord("123456");
person.setCreateTime(new Date());
//更新条件
Query query= new Query(Criteria.where("id").is(person.getId()));
//更新值
Update update= new Update().set("userName", person.getUserName()).set("passWord", person.getPassWord());
//更新查询满足条件的文档数据(第一条)
UpdateResult result =mongoTemplate.updateFirst(query,update, Person.class);
if(result!=null){
System.out.println("更新条数:" + result.getMatchedCount());
}
}
}
-
更新文档,匹配查询到的文档数据中的所有数据
@RunWith(SpringRunner.class)
@SpringBootTest
public class PersonServiceTest {
@Autowired
private MongoTemplate mongoTemplate;
/**
* 更新文档,匹配查询到的文档数据中的所有数据
* @throws Exception
*/
@Test
public void updateMany() throws Exception {
//更新对象
Person person =new Person();
person.setId(1l);
person.setUserName("张三");
person.setPassWord("123456");
person.setCreateTime(new Date());
//更新条件
Query query= new Query(Criteria.where("id").is(person.getId()));
//更新值
Update update= new Update().set("userName", person.getUserName()).set("passWord", person.getPassWord());
//更新查询满足条件的文档数据(全部)
UpdateResult result = mongoTemplate.updateMulti(query, update, Person.class);
if(result!=null){
System.out.println("更新条数:" + result.getMatchedCount());
}
}
}
删除文档
MongoTemplate提供了remove()、findAndRemove()和findAllAndRemove()方法,用于删除文档,示例代码如下:
-
删除符合条件的所有文档
@RunWith(SpringRunner.class)
@SpringBootTest
public class PersonServiceTest {
@Autowired
private MongoTemplate mongoTemplate;
/**
* 更新文档,匹配查询到的文档数据中的所有数据
* @throws Exception
*/
@Test
public void updateMany() throws Exception {
//更新对象
Person person =new Person();
person.setId(1l);
person.setUserName("张三");
person.setPassWord("123456");
person.setCreateTime(new Date());
//更新条件
Query query= new Query(Criteria.where("id").is(person.getId()));
//更新值
Update update= new Update().set("userName", person.getUserName()).set("passWord", person.getPassWord());
//更新查询满足条件的文档数据(全部)
UpdateResult result = mongoTemplate.updateMulti(query, update, Person.class);
if(result!=null){
System.out.println("更新条数:" + result.getMatchedCount());
}
}
}
-
删除符合条件的单个文档,并返回删除的文档
@RunWith(SpringRunner.class)
@SpringBootTest
public class PersonServiceTest {
@Autowired
private MongoTemplate mongoTemplate;
/**
* 删除符合条件的单个文档,并返回删除的文档
* @throws Exception
*/
@Test
public void findAndRemove() throws Exception {
Person person =new Person();
person.setId(1l);
person.setUserName("张三");
person.setPassWord("123456");
person.setCreateTime(new Date());
Query query = new Query(Criteria.where("id").is(person.getId()));
Person result = mongoTemplate.findAndRemove(query, Person.class);
System.out.println("删除的文档数据:" + result.toString());
}
}
-
删除符合条件的所有文档,并返回删除的文档
@RunWith(SpringRunner.class)
@SpringBootTest
public class PersonServiceTest {
@Autowired
private MongoTemplate mongoTemplate;
/**
* 删除符合条件的所有文档,并返回删除的文档
* @throws Exception
*/
@Test
public void findAllAndRemove() throws Exception {
Person person =new Person();
person.setId(1l);
person.setUserName("张三");
person.setPassWord("123456");
person.setCreateTime(new Date());
Query query = new Query(Criteria.where("id").is(person.getId()));
List<Person> result = mongoTemplate.findAllAndRemove(query, Person.class);
System.out.println("删除的文档数据:" + result.toString());
}
}
查询
MongoTemplate提供了非常多的文档查询方法,日常开发中用的最多的就是find()方法,示例代码如下:
-
查询集合中的全部文档数据
@RunWith(SpringRunner.class)
@SpringBootTest
public class PersonServiceTest {
@Autowired
private MongoTemplate mongoTemplate;
/**
* 查询集合中的全部文档数据
* @throws Exception
*/
@Test
public void findAll() throws Exception {
List<Person> result = mongoTemplate.findAll(Person.class);
System.out.println("查询结果:" + result.toString());
}
}
-
查询集合中指定的ID文档数据
@RunWith(SpringRunner.class)
@SpringBootTest
public class PersonServiceTest {
@Autowired
private MongoTemplate mongoTemplate;
/**
* 查询集合中指定的ID文档数据
* @throws Exception
*/
@Test
public void findById() {
long id = 1l;
Person result = mongoTemplate.findById(id, Person.class);
System.out.println("查询结果:" + result.toString());
}
}
-
根据条件查询集合中符合条件的文档,返回第一条数据
@RunWith(SpringRunner.class)
@SpringBootTest
public class PersonServiceTest {
@Autowired
private MongoTemplate mongoTemplate;
/**
* 根据条件查询集合中符合条件的文档,返回第一条数据
*/
@Test
public void findOne() {
String userName = "张三";
Query query = new Query(Criteria.where("userName").is(userName));
Person result = mongoTemplate.findOne(query, Person.class);
System.out.println("查询结果:" + result.toString());
}
}
-
根据条件查询集合中符合条件的文档
@RunWith(SpringRunner.class)
@SpringBootTest
public class PersonServiceTest {
@Autowired
private MongoTemplate mongoTemplate;
/**
* 根据条件查询集合中符合条件的文档
*/
@Test
public void findByCondition() {
String userName = "张三";
Query query = new Query(Criteria.where("userName").is(userName));
List<Person> result = mongoTemplate.find(query, Person.class);
System.out.println("查询结果:" + result.toString());
}
}
-
根据【AND】关联多个查询条件,查询集合中的文档数据
@RunWith(SpringRunner.class)
@SpringBootTest
public class PersonServiceTest {
@Autowired
private MongoTemplate mongoTemplate;
/**
* 根据【AND】关联多个查询条件,查询集合中的文档数据
*/
@Test
public void findByAndCondition() {
// 创建条件
Criteria criteriaUserName = Criteria.where("userName").is("张三");
Criteria criteriaPassWord = Criteria.where("passWord").is("123456");
// 创建条件对象,将上面条件进行 AND 关联
Criteria criteria = new Criteria().andOperator(criteriaUserName, criteriaPassWord);
// 创建查询对象,然后将条件对象添加到其中
Query query = new Query(criteria);
List<Person> result = mongoTemplate.find(query, Person.class);
System.out.println("查询结果:" + result.toString());
}
}
-
根据【OR】关联多个查询条件,查询集合中的文档数据
@RunWith(SpringRunner.class)
@SpringBootTest
public class PersonServiceTest {
@Autowired
private MongoTemplate mongoTemplate;
/**
* 根据【OR】关联多个查询条件,查询集合中的文档数据
*/
@Test
public void findByOrCondition() {
// 创建条件
Criteria criteriaUserName = Criteria.where("userName").is("张三");
Criteria criteriaPassWord = Criteria.where("passWord").is("123456");
// 创建条件对象,将上面条件进行 OR 关联
Criteria criteria = new Criteria().orOperator(criteriaUserName, criteriaPassWord);
// 创建查询对象,然后将条件对象添加到其中
Query query = new Query(criteria);
List<Person> result = mongoTemplate.find(query, Person.class);
System.out.println("查询结果:" + result.toString());
}
}
-
根据【IN】关联多个查询条件,查询集合中的文档数据
@RunWith(SpringRunner.class)
@SpringBootTest
public class PersonServiceTest {
@Autowired
private MongoTemplate mongoTemplate;
/**
* 根据【IN】关联多个查询条件,查询集合中的文档数据
*/
@Test
public void findByInCondition() {
// 设置查询条件参数
List<Long> ids = Arrays.asList(1l, 10l, 11l);
// 创建条件
Criteria criteria = Criteria.where("id").in(ids);
// 创建查询对象,然后将条件对象添加到其中
Query query = new Query(criteria);
List<Person> result = mongoTemplate.find(query, Person.class);
System.out.println("查询结果:" + result.toString());
}
}
-
根据【逻辑运算符】查询集合中的文档数据
@RunWith(SpringRunner.class)
@SpringBootTest
public class PersonServiceTest {
@Autowired
private MongoTemplate mongoTemplate;
/**
* 根据【逻辑运算符】查询集合中的文档数据
*/
@Test
public void findByOperator() {
// 设置查询条件参数
int min = 20;
int max = 35;
Criteria criteria = Criteria.where("age").gt(min).lte(max);
// 创建查询对象,然后将条件对象添加到其中
Query query = new Query(criteria);
List<Person> result = mongoTemplate.find(query, Person.class);
System.out.println("查询结果:" + result.toString());
}
}
-
根据【正则表达式】查询集合中的文档数据
@RunWith(SpringRunner.class)
@SpringBootTest
public class PersonServiceTest {
@Autowired
private MongoTemplate mongoTemplate;
/**
* 根据【正则表达式】查询集合中的文档数据
*/
@Test
public void findByRegex() {
// 设置查询条件参数
String regex = "^张*";
Criteria criteria = Criteria.where("userName").regex(regex);
// 创建查询对象,然后将条件对象添加到其中
Query query = new Query(criteria);
List<Person> result = mongoTemplate.find(query, Person.class);
System.out.println("查询结果:" + result.toString());
}
}
-
根据单个条件查询集合中的文档数据,并按指定字段进行排序与限制指定数目
@RunWith(SpringRunner.class)
@SpringBootTest
public class PersonServiceTest {
@Autowired
private MongoTemplate mongoTemplate;
/**
* 根据单个条件查询集合中的文档数据,并按指定字段进行排序与限制指定数目
*/
@Test
public void findByConditionAndSortLimit() {
String userName = "张三";
//从第一行开始,查询2条数据返回
Query query = new Query(Criteria.where("userName").is(userName)).with(Sort.by("createTime")).limit(2).skip(1);
List<Person> result = mongoTemplate.find(query, Person.class);
System.out.println("查询结果:" + result.toString());
}
}
-
统计集合中符合【查询条件】的文档【数量】
@RunWith(SpringRunner.class)
@SpringBootTest
public class PersonServiceTest {
@Autowired
private MongoTemplate mongoTemplate;
/**
* 统计集合中符合【查询条件】的文档【数量】
*/
@Test
public void countNumber() {
// 设置查询条件参数
String regex = "^张*";
Criteria criteria = Criteria.where("userName").regex(regex);
// 创建查询对象,然后将条件对象添加到其中
Query query = new Query(criteria);
long count = mongoTemplate.count(query, Person.class);
System.out.println("统计结果:" + count);
}
}
事务
单节点 mongodb 不支持事务,需要搭建 MongoDB 复制集才有事务,使用方式和mysql一样在springboot中。
------------------------------------------与正文内容无关------------------------------------ 如果觉的文章写对各位读者老爷们有帮助的话,麻烦点赞加关注呗!作者在这拜谢了!
混口饭吃了!如果你需要Java 、Python毕设、商务合作、技术交流、就业指导、技术支持度过试用期。请在关注私信我,本人看到一定马上回复!
这是我全部文章所在目录,看看是否有你需要的,如果遇到觉得不对地方请留言,看到后我会查阅进行改正。
A乐神-CSDN博客
关注在文章左上角,作者信息处。