spring mongodb分页,动态条件、字段查询
使用MongRepository
public interface VideoRepository extends MongoRepository<Video, String> {
Video findVideoById(String id);
// 视频分页预览{title,coverImg}
Page<Video> findByGradeAndCourse(Grade grade, Course course, Pageable page);
}
- 问题
- 动态条件查询?
- 只查询指定字段?
- 指定字段
@Query(fields = "{'title':1, 'coverImg':1, 'course':1}")
Page<Video> findBy(Criteria where, Pageable page);
- 指定条件
DBObject obj = new BasicDBObject();
obj.put("userId", new BasicDBObject("$gte", 2));
BasicDBObject fieldsObject = new BasicDBObject();
fieldsObject.put("userId", 1);
fieldsObject.put("name", 1);
Query query = new BasicQuery(obj.toString(), fieldsObject.toString());
- demo,使用MongoTemplate,Query,DBObject
@Override
public Result getVideos(Pageable page, Long gradeId, Long courseId) {
DBObject obj = new BasicDBObject();
if(gradeId!=null&&gradeId!=0){
obj.put("grade.id", gradeId);
}
if(gradeId!=null&&gradeId!=0){
obj.put("course.id", courseId);
}
obj.put("course.id", 2);
// obj.put("course.id", new BasicDBObject("$gte", 2));
BasicDBObject fieldsObject = new BasicDBObject();
fieldsObject.put("title", 1);
fieldsObject.put("coverImg", 1);
fieldsObject.put("course", 1);
Query query = new BasicQuery(obj.toString(), fieldsObject.toString());
query.skip(page.getOffset()).limit(page.getPageSize());
List<Video> videos = mongoTemplate.find(query, Video.class);
// 总个数
long count = mongoTemplate.count(query, Video.class);
Page<Video> result = new PageImpl<Video>(videos, page, count);
return Result.success(videos);
}
查询条件对于属性是对象(course)无法生效,该方法还是不可行
混合 (终极法器)
本质上还是使用MongoTemplate来实现的,MongoRepository能实现查询指定字段,但是不能实现动态条件查询。
MongoTemplate的find方法接收Query参数,Query可以实现动态字段,但是动态条件不是普适应的(我还没找到),对于对象属性无法查询。但是Query有一个addCriteria方法,该方法可以将Example融合到Query中。因此find方法使用了Example的动态查询,Query的动态字段查询。
- VidoeOperations
public interface VideoOperations {
Page<Video> findAllPage(Example<Video> example, DBObject fields, Pageable page);
}
- VideoRepository
public interface VideoRepository extends MongoRepository<Video, String>, VideoOperations {
Video findVideoById(String id);
}
- VideoRepositoryImpl
public class VideoRepositoryImpl implements VideoOperations {
@Autowired
private MongoTemplate mongoTemplate;
@Override
public Page<Video> findAllPage(Example<Video> example, DBObject fields, Pageable page) {
Query query = new BasicQuery(null, fields.toString());
query.addCriteria((new Criteria()).alike(example));
query.with(page);
// Query q = (new Query((new Criteria()).alike(example))).with(page);
List<Video> list = mongoTemplate.find(query, example.getProbeType());
return PageableExecutionUtils.getPage(list, page, () -> {
return mongoTemplate.count(query, example.getProbeType());
});
}
}
Keyword | Sample | Logical result |
---|---|---|
After |
findByBirthdateAfter(Date date) |
{"birthdate" : {"$gt" : date}} |
GreaterThan |
findByAgeGreaterThan(int age) |
{"age" : {"$gt" : age}} |
GreaterThanEqual |
findByAgeGreaterThanEqual(int age) |
{"age" : {"$gte" : age}} |
Before |
findByBirthdateBefore(Date date) |
{"birthdate" : {"$lt" : date}} |
LessThan |
findByAgeLessThan(int age) |
{"age" : {"$lt" : age}} |
LessThanEqual |
findByAgeLessThanEqual(int age) |
{"age" : {"$lte" : age}} |
Between |
findByAgeBetween(int from, int to) |
{"age" : {"$gt" : from, "$lt" : to}} |
In |
findByAgeIn(Collection ages) |
{"age" : {"$in" : [ages…]}} |
NotIn |
findByAgeNotIn(Collection ages) |
{"age" : {"$nin" : [ages…]}} |
IsNotNull , NotNull |
findByFirstnameNotNull() |
{"firstname" : {"$ne" : null}} |
IsNull , Null |
findByFirstnameNull() |
{"firstname" : null} |
Like , StartingWith , EndingWith |
findByFirstnameLike(String name) |
{"firstname" : name} (name as regex) |
NotLike , IsNotLike |
findByFirstnameNotLike(String name) |
{"firstname" : { "$not" : name }} (name as regex) |
Containing on String |
findByFirstnameContaining(String name) |
{"firstname" : name} (name as regex) |
NotContaining on String |
findByFirstnameNotContaining(String name) |
{"firstname" : { "$not" : name}} (name as regex) |
Containing on Collection |
findByAddressesContaining(Address address) |
{"addresses" : { "$in" : address}} |
NotContaining on Collection |
findByAddressesNotContaining(Address address) |
{"addresses" : { "$not" : { "$in" : address}}} |
Regex |
findByFirstnameRegex(String firstname) |
{"firstname" : {"$regex" : firstname }} |
(No keyword) |
findByFirstname(String name) |
{"firstname" : name} |
Not |
findByFirstnameNot(String name) |
{"firstname" : {"$ne" : name}} |
Near |
findByLocationNear(Point point) |
{"location" : {"$near" : [x,y]}} |
Near |
findByLocationNear(Point point, Distance max) |
{"location" : {"$near" : [x,y], "$maxDistance" : max}} |
Near |
findByLocationNear(Point point, Distance min, Distance max) |
{"location" : {"$near" : [x,y], "$minDistance" : min, "$maxDistance" : max}} |
Within |
findByLocationWithin(Circle circle) |
{"location" : {"$geoWithin" : {"$center" : [ [x, y], distance]}}} |
Within |
findByLocationWithin(Box box) |
{"location" : {"$geoWithin" : {"$box" : [ [x1, y1], x2, y2]}}} |
IsTrue , True |
findByActiveIsTrue() |
{"active" : true} |
IsFalse , False |
findByActiveIsFalse() |
{"active" : false} |
Exists |
findByLocationExists(boolean exists) |
{"location" : {"$exists" : exists }} |
spring mongodb分页,动态条件、字段查询的更多相关文章
- spring boot jpa 多条件组合查询带分页的案例
spring data jpa 是一个封装了hebernate的dao框架,用于单表操作特别的方便,当然也支持多表,只不过要写sql.对于单表操作,jpake可以通过各种api进行搞定,下面是一个对一 ...
- spring JPA分页排序条件查询
@RequestMapping("/listByPage") public Page<Production> listByPage(int page, int size ...
- mapper分页排序指定字段查询模板
StudentQuery: package Student; import java.util.ArrayList; import java.util.List; public class Stude ...
- 【spring data jpa】带有条件的查询后分页和不带条件查询后分页实现
一.不带有动态条件的查询 分页的实现 实例代码: controller:返回的是Page<>对象 @Controller @RequestMapping(value = "/eg ...
- MongoDB 分页查询的方法及性能
最近有点忙,本来有好多东西可以总结,Redis系列其实还应该有四.五.六...不过<Redis in Action>还没读完,等读完再来总结,不然太水,对不起读者. 自从上次Redis之后 ...
- C#MongoDB 分页查询的方法及性能
传统的SQL分页 传统的sql分页,所有的方案几乎是绕不开row_number的,对于需要各种排序,复杂查询的场景,row_number就是杀手锏.另外,针对现在的web很流行的poll/push加载 ...
- SpringDataJPA+QueryDSL玩转态动条件/投影查询
在本文之前,本应当专门有一篇博客讲解SpringDataJPA使用自带的Specification+JpaSpecificationExecutor去说明如何玩条件查询,但是看到新奇.编码更简单易懂的 ...
- Spring Boot Jpa 多条件查询+排序+分页
事情有点多,于是快一个月没写东西了,今天补上上次说的. JPA是Java Persistence API的简称,中文名Java持久层API,是JDK 5.0注解或XML描述对象-关系表的映射关系,并将 ...
- Spring Data JPA,一种动态条件查询的写法
我们在使用SpringData JPA框架时,进行条件查询,如果是固定条件的查询,我们可以使用符合框架规则的自定义方法以及@Query注解实现. 如果是查询条件是动态的,框架也提供了查询接口. Jpa ...
随机推荐
- java.lang.IncompatibleClassChangeError:可以考虑是否是jar包冲突
一.背景:启动tomcat的时候,报错: java.lang.IncompatibleClassChangeError: class org.springframework.core.type.cla ...
- Prufer codes与Generalized Cayley's Formula学习笔记
\(Prufer\)序列 在一棵\(n\)个点带标号无根树里,我们定义这棵树的\(Prufer\)序列为执行以下操作后得到的序列 1.若当前树中只剩下两个节点,退出,否则执行\(2\) 2.令\(u\ ...
- django rest framework实现分页功能
在web开发中很多需求都需要实现分页功能,然而 Django Rest Framework 自带的分页功能,只能在 mixins.ListModelMixin and generics.Generic ...
- Python(序列化json,pickle,shelve)
序列化 参考:https://www.cnblogs.com/yuanchenqi/articles/5732581.html # dic = str({'1':'111'}) # # f = ope ...
- WC2019 全国模拟赛第一场 T1 题解
由于只会T1,没法写游记,只好来写题解了... 题目链接 题目大意 给你一个数列,每次可以任取两个不相交的区间,取一次的贡献是这两个区间里所有数的最小值,求所有取法的贡献和,对 \(10^9+7\) ...
- robot framework学习笔记之十一--第三方库requests详解
一.安装 Requests 通过pip安装 pip install requests 或者,下载代码后安装: $ git clone git://github.com/kennethreitz/req ...
- logstash5.5.0同步sql server数据
注意:jdbc.conf和jdbc.sql文件编码都为ANSI jdbc.conf内容如下: input { stdin { } jdbc { jdbc_connection_string => ...
- CUDA安装
1.CUDA是什么? CUDA(Compute Unified Device Architecture),显卡厂商NVidia推出的运算平台. 随着显卡的发展,GPU越来越强大,而且GPU为显示图像做 ...
- 工具篇-大数据组件的一些快捷Shell操作
一.Hbase 1. HBase shell窗口进入 执行hbase shell 2. HBase表的创建 # 语法:create <table>, {NAME => <fam ...
- 汉诺塔的python 动画演示
1.简介 古代有一座汉诺塔,塔内有3个座A.B.C,A座上有n个盘子,盘子大小不等,大的在下,小的在上,如图所示.有一个和尚想把这n个盘子从A座移到C座,但每次只能移动一个盘子,并且自移动过程中,3个 ...