1. SpringBoot 集成 MongoTemplate
1.1 添加依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-mongodb</artifactId>
<version>2.0.0.RELEASE</version>
</dependency>
1.2 添加配置
spring:
data:
mongodb:
uri: mongodb://192.168.8.105:27017/test
1.3 添加实体
import lombok.Data;
import org.springframework.data.mongodb.core.mapping.Document;
@Data
@Document(value = "personalContribution")
public class PersonalContribution {
public static String COLLECTION_NAME = "personalContribution";
/**
* 资源ID
*/
private Long resourceId;
}
2. MongoTemplate 操作
2.1 查询
# Query
Query query = new Query();
# Eq 精准查找
query.addCriteria(Criteria.where(PersonalContribution.RESOURCE_TYPE).is(resourceType));
# Like 模糊查找
query.addCriteria(Criteria.where(PersonalContribution.TITLE).regex(".*?\\" + title + ".*"));
# Between 范围查找
query.addCriteria(Criteria.where(PersonalContribution.UPLOAD_DATE).gte(startDate.getTime()));
query.addCriteria(Criteria.where(PersonalContribution.UPLOAD_DATE).lte(endDate.getTime()));
# In 范围查找
query.addCriteria(Criteria.where(PersonalContribution.RESOURCE_ID).in(resourceIds));
# Sort 排序
query.with(Sort.by(
Sort.Order.desc(orderById)
));
query.with(Sort.by(
Sort.Order.asc(orderById)
));
# Limit 分页
query.skip(current.intValue());
query.limit(size.intValue());
# 查询总数
long count = mongoTemplate.count(query, PersonalContribution.COLLECTION_NAME);
# 查询单个
mongoTemplate.findOne(query, PersonalContribution.class, PersonalContribution.COLLECTION_NAME)
# 查询集合
mongoTemplate.find(query, PersonalContribution.class, PersonalContribution.COLLECTION_NAME)
2.2 新增
# 单个
PersonalContribution personalContribution = new PersonalContribution ();
mongoTemplate.insert(personalContribution);
# 批量
List<PersonalContribution> personalContributions = new ArrayList();
mongoTemplate.insertAll(personalContributions);
2.3 修改
mongoTemplate.updateMulti(
new Query()
.addCriteria(
Criteria.where(PersonalContribution.RESOURCE_ID)
.is(resourceId)),
Update.update(PersonalContribution.APPROVAL_STATUS, applyStatus),
PersonalContribution.COLLECTION_NAME
);
2.4 删除
mongoTemplate.remove(
new Query()
.addCriteria(
Criteria.where(PersonalContribution.RESOURCE_ID)
.is(resourceId)),
PersonalContribution.class,
collectionName
);