使用springData操作mongo
Posted 好大的月亮
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了使用springData操作mongo相关的知识,希望对你有一定的参考价值。
上依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-mongodb</artifactId>
</dependency>
配置
spring:
data:
mongodb:
host: xxx.xxx.xxx.xxx
port: 27017
username: fchan
password: '10086' #这里要注意如果是存数字密码需要用字符串包裹
database: test #实际操作db
authentication-database: admin #鉴权db
可以看到在MongoProperties
中,密码是用char
存的,char
是16
位的,最大可以存65535
,那么问题来了,一串数字密码可能正好存到了一个char
里,原本可能长度=5
的密码变成了长度=1
的char
,然后验证密码的时候就gg
了。
curd代码
实体类
package com.felix.spring_cloud_one.document;
import org.springframework.data.annotation.Id;
import org.springframework.data.mongodb.core.mapping.Document;
import java.io.Serializable;
@Document(collection = "user")
public class UserDocument implements Serializable
private static final long serialVersionUID = -6572688910937746087L;
@Id //【主键是自动生成的】
private String id;
private String userName;
private Integer age;
private String password;
private String address;
public String getId()
return id;
public void setId(String id)
this.id = id;
public String getUsername()
return userName;
public void setUsername(String userName)
this.userName = userName;
public Integer getAge()
return age;
public void setAge(Integer age)
this.age = age;
public String getPassword()
return password;
public void setPassword(String password)
this.password = password;
public String getAddress()
return address;
public void setAddress(String address)
this.address = address;
插入
public String add()
UserDocument userDocument = new UserDocument();
userDocument.setAge(11);
userDocument.setPassword("123");
userDocument.setUsername("小明");
userDocument.setAddress("北京");
UserDocument afterInsert = mongoTemplate.insert(userDocument);
return afterInsert.getId();
批量插入
public Object batchAdd()
List<UserDocument> list = new ArrayList<>();
for (int i = 0; i < 10; i ++)
list.add(getUserDocument("大宝贝" + i, i + 10));
Collection<UserDocument> batchResult = mongoTemplate.insert(list, UserDocument.class);
return batchResult;
查询
public Object findById(String id)
UserDocument byId = mongoTemplate.findById(id, UserDocument.class);
return byId;
public Object findByCondition(String name, Integer age, String address)
Criteria criteria = new Criteria();
if(Objects.nonNull(name))
criteria = where("userName").is(name);
if(Objects.nonNull(age))
criteria = criteria.and("age").is(age);
if(Objects.nonNull(address))
criteria = criteria.and("address").is(address);
Query query = new Query(
criteria
);
List<UserDocument> userDocuments = mongoTemplate.find(query, UserDocument.class);
return userDocuments;
public Object findUsersLikeName(String name)
//正则表达式 模糊查询【】
String regex = String.format("%s%s%s", "^.*", name, ".*$");
Pattern pattern = Pattern.compile(regex, Pattern.CASE_INSENSITIVE);
//名字符合正则表达式的条件
Query query = new Query(where("userName").regex(pattern));
//mongodb 文档相对应的模型类
List<UserDocument> userList = mongoTemplate.find(query, UserDocument.class);
return userList;
public Object findUsersPage(String name, Integer pageNo, Integer pageSize)
//构造条件
Query query = new Query();
//正则表达式匹配
String regex = String.format("%s%s%s", "^.*", name, ".*$");
Pattern pattern = Pattern.compile(regex, Pattern.CASE_INSENSITIVE);
//添加条件
query.addCriteria(where("userName").regex(pattern));
//开始统计记录数
int totalCount = (int) mongoTemplate.count(query, UserDocument.class);
//分页查询 返回结果
List<UserDocument> userList = mongoTemplate.find(query.skip((pageNo - 1) * pageSize).limit(pageSize), UserDocument.class);
Map<String, Object> pageMap = new HashMap<>();
pageMap.put("list", userList);
pageMap.put("totalCount",totalCount);
return pageMap;
更新
public Object updateUser(String id, String name)
//修改一般是查询出来整个文档【document mongodb里面的叫法】
UserDocument user = mongoTemplate.findById(id, UserDocument.class);
user.setUsername(name);
//修改好相应的数据 根据id进行修改 id是查询出来的
Query query = new Query(where("_id").is(user.getId()));
Update update = new Update();
update.set("userName", user.getUsername());
//执行更新
UpdateResult result = mongoTemplate.upsert(query, update, UserDocument.class);
return result;
批量更新
public Object batchUpdate(String name)
Query query = new Query();
query.addCriteria(
where("userName").regex("^大宝贝.*$")
);
List<UserDocument> needUpdateList = mongoTemplate.find(query, UserDocument.class);
BulkOperations bulkOperations = mongoTemplate.bulkOps(BulkOperations.BulkMode.UNORDERED, UserDocument.class);
for (UserDocument userDocument : needUpdateList)
Update update = new Update();
update.set("userName", "大大" + name);
bulkOperations.updateOne(new Query().addCriteria(Criteria.where("_id").is(userDocument.getId())), update);
bulkOperations.execute();
return null;
删除
public Object delete(String id)
//构造条件 根据id删除相应的文档
Query query =
new Query(where("_id").is(id));
DeleteResult result = mongoTemplate.remove(query, UserDocument.class);
return result;
以上是关于使用springData操作mongo的主要内容,如果未能解决你的问题,请参考以下文章
jpa pagingandsortingrepository啥情况会过滤条件查询