一、准备项目
二、导入pom依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-mongodb</artifactId>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
三、yml配置文件
spring:
data:
mongodb:
uri: mongodb://用户名:密码@服务器:端口/?authSource=admin
database: 数据库名称
四、实体类
User.java
package com.mongo.springmongo.Pojo;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.springframework.data.annotation.Id;
import org.springframework.data.mongodb.core.mapping.Document;
@Data
@NoArgsConstructor
@AllArgsConstructor
@Document("user")
public class User {
@Id
private String _id;
private String name;
private String age;
private String sex;
}
五、测试 MongoTemplate 操作mongo库
操作前先导入mongoTemplate
@Resource
private MongoTemplate mongoTemplate;
1、查询用户
//查全部
@Test
void findAll(){
List<User> list =mongoTemplate.findAll(User.class);
System.out.println(list);
}
2、添加用户
//添加
@Test
void insert(){
User user=new User();
user.setName("骞子");
user.setSex("男");
user.setAge("21");
//把user传入mongoTemplate中
User userMap=mongoTemplate.insert(user);
System.out.println(userMap);
}
3、根据id修改用户
//根据id修改数据
@Test
void updateById(){
//根据id查询
User user = mongoTemplate.findById("63a1ba17ab970a3a7c347191", User.class);
//修改值
user.setAge("21");
user.setName("典猪");
user.setSex("男");
//调用方法
Query query = new Query(Criteria.where("_id").is(user.get_id()));
Update update = new Update();
update.set("name", user.getName());
update.set("age", user.getAge());
update.set("sex", user.getSex());
UpdateResult upsert = mongoTemplate.upsert(query, update, User.class);
long count = upsert.getModifiedCount();
if (count>0){
System.out.println("================成功:" + count);
}else{
System.out.println("================失败:" + count);
}
}
4、根据id删除用户
//根据id删除
@Test
void deleteById(){
//调用方法
Query query=new Query(Criteria.where("_id").is("63a1c27da38d0934fe9c1f84"));
DeleteResult remove=mongoTemplate.remove(query,User.class);
long count= remove.getDeletedCount();
if (count>0){
System.out.println("======成功"+count);
}else{
System.out.println("======失败"+count);
}
}
5、根据姓名模糊查询
//模糊查询
@Test
public void vague(){
String name = "猪";
String regex = String.format("%s%s%s", "^.*", name, ".*$");
Pattern pattern = Pattern.compile(regex,Pattern.CASE_INSENSITIVE);
Query query = new Query(
Criteria.where("name").regex(pattern));
List<User> user = mongoTemplate.find(query, User.class);
System.out.println("==================>>>>>>"+user);
}
版权声明:本文为shshhshshh原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。