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 ...
随机推荐
- django系列6--Ajax05 请求头ContentType, 使用Ajax上传文件
一.请求头ContentType ContentType指的是请求体的编码类型,常见的类型共有三种: 1.application/x-www-form-urlencoded 这应该是最常见的 POST ...
- 【OCP-12c】CUUG 071题库考试原题及答案解析(20)
20.choose two Examine the description of the EMP_DETAILS table given below: Which two statements are ...
- leecode刷题(16)-- 字符串转换整数
leecode刷题(16)-- 字符串转换整数 字符串转换整数 描述: 请你来实现一个 atoi 函数,使其能将字符串转换成整数. 首先,该函数会根据需要丢弃无用的开头空格字符,直到寻找到第一个非空格 ...
- Ionic2 自学须知的基本知识点
http://www.cnblogs.com/zsl123/p/5991336.html Ionic(ionicframework)一款接近原生的HTML5移动App开发框架. IONIC 是目前最有 ...
- 代码 | 自适应大邻域搜索系列之(4) - Solution定义和管理的代码实现解析
前言 上一篇讲解了destroy和repair方法的具体实现代码,好多读者都在喊酸爽和得劲儿--今天这篇就讲点简单的,关于solution的定义和管理的代码实现,让大家回回神吧--哈哈. 01 总体概 ...
- C#-WebForm-GridView表格展示数据
GrideView 控件,功能是将数据库的数据用表格的形式展示在页面上 一.<源>代码中放入 GridView 控件 打开<设计>界面 二.绑定数据源 (一)创建 LinQ 类 ...
- 【Jenkins】定时构建语法
跟cron定时任务语法基本类似 一.字段有哪些 每行包含5个字段,用制表符或空格隔开,从左至右依次是: 分 时 天 月 星期 二.每个字段的取值范围 分钟 (0–59) 时 (0–23) 天 (1–3 ...
- SpringMVC的 @RestController和@Controller 区别
@RestController注解,相当于@Controller+@ResponseBody两个注解的结合, 返回json数据不需要在方法前面加@ResponseBody注解了,但使用@RestCon ...
- Q147 对链表进行插入排序
插入排序的动画演示如上.从第一个元素开始,该链表可以被认为已经部分排序(用黑色表示). 每次迭代时,从输入数据中移除一个元素(用红色表示),并原地将其插入到已排好序的链表中. 插入排序算法: 插入排序 ...
- 20190417 CentOS 7下安装ActiveMQ
前言 用VMware安装CentOS 7.6,创建一个新的用户lihailin9073,并使用这个用户登陆CentOS系统 安装和启动 登陆ActivieMQ官网http://activemq.apa ...