springMVC操作mongoDB增删改查
时间:2021-07-01 10:21:17
帮助过:3人阅读
class NewsHelpService {
@Resource
private MongoTemplate mongoTemplate;
//add
public void insert(NewsHelp newsHelp) {
mongoTemplate.insert(newsHelp);
}
//select
public Pagination<NewsHelp>
findNewsHelpAll(String type, String title, String id, Integer pageNo,
Integer pageSize) {
// QueryPage page = QueryPage.build(pageNo, pageSize);
MandoAssert.notNull(type, "类型不能为空"
);
Criteria criteria = Criteria.where("type"
).is(type);
if (title!=
null) {
Pattern pattern =
Pattern.compile(title, Pattern.CASE_INSENSITIVE); //模糊查询
criteria.andOperator(Criteria.where("title"
).regex(pattern));
}
if (id!=
null) {
criteria.andOperator(Criteria.where("id"
).is(id));
}
Query query =
BasicQuery.query(criteria);
long total = mongoTemplate.count(query, NewsHelp.
class);
Pagination<NewsHelp> newsHelps =
new Pagination<NewsHelp>
(pageNo, pageSize);
int skip = (pageNo-1)*
pageSize;
if (pageSize<1
) {
query.skip(skip);// skip相当于从那条记录开始
query.limit(pageSize);
// 从skip开始,取多少条记录
}
List<NewsHelp> datas = mongoTemplate.find(query, NewsHelp.
class);
newsHelps.setData(datas);//获取数据
newsHelps.setTotal((int)total);
return newsHelps;
}
//selectOne
public NewsHelp findNewsHelp(String id) {
Query query = BasicQuery.query(Criteria.where("id"
).is(id));
NewsHelp newsHelp = mongoTemplate.findOne(query, NewsHelp.
class);
return newsHelp;
}
// update 新闻类
public void updateNewsHelp(NewsHelp help) {
MandoAssert.notNull(help.getId(), "ID不能为空"
);
Update update =
new Update();
if(
null!=
help.getTops()){
update.set("tops"
, help.getTops());
}
if(StringUtils.isNotEmpty(help.getTitle())){
update.set("title"
, help.getTitle());
}
if(StringUtils.isNotEmpty(help.getContent())){
update.set("content"
, help.getContent());
}
update.set("modifyDate",
new Date());
mongoTemplate.updateMulti(Query.query(Criteria.where("id").is(help.getId())),update,NewsHelp.
class);
}
//delete
public void delNewsHelp(List<String>
ids) {
ids.stream().forEach(id ->
{
Query query = BasicQuery.query(Criteria.where("id"
).is(id));
mongoTemplate.findAndRemove(query, NewsHelp.class);
});
}
}
偶遇晨光原创
下面讲解一下springMVC+mongodb配置
springMVC操作mongoDB增删改查
标签: