spring boot学习第九篇:操作mongo的集合和集合中的数据

1、安装好了Mongodb

参考:ubuntu安装mongod、配置用户访问、添删改查-CSDN博客

2、pom.xml文件内容如下:

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd"><modelVersion>4.0.0</modelVersion><parent><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-parent</artifactId><version>2.6.4</version><relativePath/> <!-- lookup parent from repository --></parent><groupId>com.hmblogs</groupId><artifactId>hmblogs</artifactId><version>0.0.1-SNAPSHOT</version><name>hmblogs</name><description>hmblogs</description><properties><java.version>8</java.version><druid.version>1.2.8</druid.version><log4jdbc.version>1.16</log4jdbc.version><es.version>7.9.2</es.version></properties><dependencies><!-- druid数据源驱动 --><dependency><groupId>com.alibaba</groupId><artifactId>druid-spring-boot-starter</artifactId><version>${druid.version}</version></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter</artifactId></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-test</artifactId><scope>test</scope></dependency><!-- mybatis --><dependency><groupId>com.baomidou</groupId><artifactId>mybatis-plus-boot-starter</artifactId><version>3.5.3.1</version></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-web</artifactId></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-test</artifactId></dependency><dependency><groupId>org.projectlombok</groupId><artifactId>lombok</artifactId><optional>true</optional></dependency><!--Mysql依赖包--><dependency><groupId>mysql</groupId><artifactId>mysql-connector-java</artifactId><scope>runtime</scope></dependency><!--lombok插件--><dependency><groupId>org.projectlombok</groupId><artifactId>lombok</artifactId><optional>true</optional></dependency><!--监控sql日志--><dependency><groupId>org.bgee.log4jdbc-log4j2</groupId><artifactId>log4jdbc-log4j2-jdbc4.1</artifactId><version>${log4jdbc.version}</version></dependency><dependency><groupId>com.alibaba</groupId><artifactId>fastjson</artifactId><version>1.2.9</version></dependency><dependency><groupId>redis.clients</groupId><artifactId>jedis</artifactId></dependency><dependency><groupId>org.apache.kafka</groupId><artifactId>kafka-clients</artifactId></dependency><dependency><groupId>org.springframework.kafka</groupId><artifactId>spring-kafka</artifactId></dependency><!-- high client--><dependency><groupId>org.elasticsearch.client</groupId><artifactId>elasticsearch-rest-high-level-client</artifactId><version>${es.version}</version><exclusions><exclusion><groupId>org.elasticsearch</groupId><artifactId>elasticsearch</artifactId></exclusion><exclusion><groupId>org.elasticsearch.client</groupId><artifactId>elasticsearch-rest-client</artifactId></exclusion></exclusions></dependency><!-- rest-high-level-client 依赖如下2个jar --><dependency><groupId>org.elasticsearch</groupId><artifactId>elasticsearch</artifactId><version>${es.version}</version></dependency><dependency><groupId>org.elasticsearch.client</groupId><artifactId>elasticsearch-rest-client</artifactId><version>${es.version}</version></dependency><dependency><groupId>junit</groupId><artifactId>junit</artifactId></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-data-mongodb</artifactId></dependency></dependencies><build><plugins><plugin><groupId>org.springframework.boot</groupId><artifactId>spring-boot-maven-plugin</artifactId></plugin></plugins></build></project>

3、application.yml文件内容如下:

server:port: 8081servlet.context-path: /#配置数据源
spring:datasource:druid:db-type: com.alibaba.druid.pool.DruidDataSourcedriverClassName: net.sf.log4jdbc.sql.jdbcapi.DriverSpyurl: jdbc:log4jdbc:mysql://${DB_HOST:localhost}:${DB_PORT:3306}/${DB_NAME:eladmin}?serverTimezone=Asia/Shanghai&characterEncoding=utf8&useSSL=falseusername: ${DB_USER:root}password: ${DB_PWD:密码}redis:host: localhostport: 6379password: hemingdatabase: 10data:mongodb:uri: mongodb://hmblogs:密码@43.138.0.199:27017/hmblogses:host: 43.138.0.199port: 9200scheme: http

4、UserEntity文件内容如下:

package com.hmblogs.backend.entity;import lombok.Data;import java.io.Serializable;@Data
public class UserEntity implements Serializable {private static final long serialVersionUID = -3258839839160856613L;private Long id;private String userName;private String passWord;//getter、setter省略
}

5、UserDaoImpl文件内容如下:

package com.hmblogs.backend.dao;import com.hmblogs.backend.entity.UserEntity;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.stereotype.Component;@Component
public class UserDaoImpl implements UserDao {@Autowiredprivate MongoTemplate mongoTemplate;/*** 创建对象* @param user*/@Overridepublic void saveUser(UserEntity user) {mongoTemplate.save(user);}/*** 根据用户名查询对象* @param userName* @return*/@Overridepublic UserEntity findUserByUserName(String userName) {Query query=new Query(Criteria.where("userName").is(userName));UserEntity user =  mongoTemplate.findOne(query , UserEntity.class);return user;}/*** 更新对象* @param user*/@Overridepublic void updateUser(UserEntity user) {Query query=new Query(Criteria.where("id").is(user.getId()));Update update= new Update().set("userName", user.getUserName()).set("passWord", user.getPassWord());//更新查询返回结果集的第一条mongoTemplate.updateFirst(query,update,UserEntity.class);//更新查询返回结果集的所有// mongoTemplate.updateMulti(query,update,UserEntity.class);}/*** 删除对象* @param id*/@Overridepublic void deleteUserById(Long id) {Query query=new Query(Criteria.where("id").is(id));mongoTemplate.remove(query,UserEntity.class);}
}

6、UserDao文件内容如下:

package com.hmblogs.backend.dao;import com.hmblogs.backend.entity.UserEntity;public interface UserDao {public void saveUser(UserEntity user);public UserEntity findUserByUserName(String userName);public void updateUser(UserEntity user);public void deleteUserById(Long id);}

7、测试验证类,内容如下:

package com.hmblogs.backend.util;import com.hmblogs.backend.dao.UserDao;
import com.hmblogs.backend.entity.UserEntity;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;@RunWith(SpringRunner.class)
@SpringBootTest
public class UserDaoTest {@Autowiredprivate UserDao userDao;@Testpublic void testSaveUser() throws Exception {UserEntity user=new UserEntity();user.setId(2l);user.setUserName("小明");user.setPassWord("fffooo123");userDao.saveUser(user);}@Testpublic void findUserByUserName(){UserEntity user= userDao.findUserByUserName("小明");System.out.println("user is "+user);}@Testpublic void updateUser(){UserEntity user=new UserEntity();user.setId(2l);user.setUserName("天空");user.setPassWord("fffxxxx");userDao.updateUser(user);}@Testpublic void deleteUserById(){userDao.deleteUserById(1l);}}

执行报错testSaveUser()方法,执行报错:

org.springframework.data.mongodb.UncategorizedMongoDbException: Exception authenticating MongoCredential{mechanism=SCRAM-SHA-1, userName='hmblogs', source='hmblogs', password=<hidden>, mechanismProperties=<hidden>}; nested exception is com.mongodb.MongoSecurityException: Exception authenticating MongoCredential{mechanism=SCRAM-SHA-1, userName='hmblogs', source='hmblogs', password=<hidden>, mechanismProperties=<hidden>}at org.springframework.data.mongodb.core.MongoExceptionTranslator.translateExceptionIfPossible(MongoExceptionTranslator.java:140)at org.springframework.data.mongodb.core.MongoTemplate.potentiallyConvertRuntimeException(MongoTemplate.java:2906)at org.springframework.data.mongodb.core.MongoTemplate.execute(MongoTemplate.java:557)at org.springframework.data.mongodb.core.MongoTemplate.saveDocument(MongoTemplate.java:1508)at org.springframework.data.mongodb.core.MongoTemplate.doSave(MongoTemplate.java:1444)at org.springframework.data.mongodb.core.MongoTemplate.save(MongoTemplate.java:1387)at org.springframework.data.mongodb.core.MongoTemplate.save(MongoTemplate.java:1372)at com.hmblogs.backend.dao.UserDaoImpl.saveUser(UserDaoImpl.java:23)at com.hmblogs.backend.util.UserDaoTest.testSaveUser(UserDaoTest.java:24)at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)at java.lang.reflect.Method.invoke(Method.java:498)at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:59)at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:56)at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)at org.springframework.test.context.junit4.statements.RunBeforeTestExecutionCallbacks.evaluate(RunBeforeTestExecutionCallbacks.java:74)at org.springframework.test.context.junit4.statements.RunAfterTestExecutionCallbacks.evaluate(RunAfterTestExecutionCallbacks.java:84)at org.springframework.test.context.junit4.statements.RunBeforeTestMethodCallbacks.evaluate(RunBeforeTestMethodCallbacks.java:75)at org.springframework.test.context.junit4.statements.RunAfterTestMethodCallbacks.evaluate(RunAfterTestMethodCallbacks.java:86)at org.springframework.test.context.junit4.statements.SpringRepeat.evaluate(SpringRepeat.java:84)at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:366)at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:251)at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:97)at org.junit.runners.ParentRunner$4.run(ParentRunner.java:331)at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:79)at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:329)at org.junit.runners.ParentRunner.access$100(ParentRunner.java:66)at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:293)at org.springframework.test.context.junit4.statements.RunBeforeTestClassCallbacks.evaluate(RunBeforeTestClassCallbacks.java:61)at org.springframework.test.context.junit4.statements.RunAfterTestClassCallbacks.evaluate(RunAfterTestClassCallbacks.java:70)at org.junit.runners.ParentRunner$3.evaluate(ParentRunner.java:306)at org.junit.runners.ParentRunner.run(ParentRunner.java:413)at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.run(SpringJUnit4ClassRunner.java:190)at org.junit.runner.JUnitCore.run(JUnitCore.java:137)at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:69)at com.intellij.rt.junit.IdeaTestRunner$Repeater$1.execute(IdeaTestRunner.java:38)at com.intellij.rt.execution.junit.TestsRepeater.repeat(TestsRepeater.java:11)at com.intellij.rt.junit.IdeaTestRunner$Repeater.startRunnerWithArgs(IdeaTestRunner.java:35)at com.intellij.rt.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:232)at com.intellij.rt.junit.JUnitStarter.main(JUnitStarter.java:55)
Caused by: com.mongodb.MongoSecurityException: Exception authenticating MongoCredential{mechanism=SCRAM-SHA-1, userName='hmblogs', source='hmblogs', password=<hidden>, mechanismProperties=<hidden>}at com.mongodb.internal.connection.SaslAuthenticator.wrapException(SaslAuthenticator.java:273)at com.mongodb.internal.connection.SaslAuthenticator.getNextSaslResponse(SaslAuthenticator.java:137)at com.mongodb.internal.connection.SaslAuthenticator.access$100(SaslAuthenticator.java:48)at com.mongodb.internal.connection.SaslAuthenticator$1.run(SaslAuthenticator.java:63)at com.mongodb.internal.connection.SaslAuthenticator$1.run(SaslAuthenticator.java:57)at com.mongodb.internal.connection.SaslAuthenticator.doAsSubject(SaslAuthenticator.java:280)at com.mongodb.internal.connection.SaslAuthenticator.authenticate(SaslAuthenticator.java:57)at com.mongodb.internal.connection.DefaultAuthenticator.authenticate(DefaultAuthenticator.java:55)at com.mongodb.internal.connection.InternalStreamConnectionInitializer.authenticate(InternalStreamConnectionInitializer.java:207)at com.mongodb.internal.connection.InternalStreamConnectionInitializer.finishHandshake(InternalStreamConnectionInitializer.java:81)at com.mongodb.internal.connection.InternalStreamConnection.open(InternalStreamConnection.java:185)at com.mongodb.internal.connection.UsageTrackingInternalConnection.open(UsageTrackingInternalConnection.java:54)at com.mongodb.internal.connection.DefaultConnectionPool$PooledConnection.open(DefaultConnectionPool.java:538)at com.mongodb.internal.connection.DefaultConnectionPool$OpenConcurrencyLimiter.openWithConcurrencyLimit(DefaultConnectionPool.java:914)at com.mongodb.internal.connection.DefaultConnectionPool$OpenConcurrencyLimiter.openOrGetAvailable(DefaultConnectionPool.java:855)at com.mongodb.internal.connection.DefaultConnectionPool.get(DefaultConnectionPool.java:173)at com.mongodb.internal.connection.DefaultConnectionPool.get(DefaultConnectionPool.java:162)at com.mongodb.internal.connection.DefaultServer.getConnection(DefaultServer.java:101)at com.mongodb.internal.binding.ClusterBinding$ClusterBindingConnectionSource.getConnection(ClusterBinding.java:175)at com.mongodb.client.internal.ClientSessionBinding$SessionBindingConnectionSource.getConnection(ClientSessionBinding.java:188)at com.mongodb.internal.operation.OperationHelper.withSuppliedResource(OperationHelper.java:581)at com.mongodb.internal.operation.OperationHelper.lambda$withSourceAndConnection$3(OperationHelper.java:563)at com.mongodb.internal.operation.OperationHelper.withSuppliedResource(OperationHelper.java:589)at com.mongodb.internal.operation.OperationHelper.withSourceAndConnection(OperationHelper.java:562)at com.mongodb.internal.operation.MixedBulkWriteOperation.lambda$execute$3(MixedBulkWriteOperation.java:232)at com.mongodb.internal.async.function.RetryingSyncSupplier.get(RetryingSyncSupplier.java:65)at com.mongodb.internal.operation.MixedBulkWriteOperation.execute(MixedBulkWriteOperation.java:268)at com.mongodb.internal.operation.MixedBulkWriteOperation.execute(MixedBulkWriteOperation.java:84)at com.mongodb.client.internal.MongoClientDelegate$DelegateOperationExecutor.execute(MongoClientDelegate.java:212)at com.mongodb.client.internal.MongoCollectionImpl.executeSingleWriteRequest(MongoCollectionImpl.java:1010)at com.mongodb.client.internal.MongoCollectionImpl.executeReplaceOne(MongoCollectionImpl.java:568)at com.mongodb.client.internal.MongoCollectionImpl.replaceOne(MongoCollectionImpl.java:551)at org.springframework.data.mongodb.core.MongoTemplate.lambda$saveDocument$18(MongoTemplate.java:1540)at org.springframework.data.mongodb.core.MongoTemplate.execute(MongoTemplate.java:555)... 39 more
Caused by: com.mongodb.MongoCommandException: Command failed with error 18 (AuthenticationFailed): 'Authentication failed.' on server 43.138.0.199:27017. The full response is {"ok": 0.0, "errmsg": "Authentication failed.", "code": 18, "codeName": "AuthenticationFailed"}at com.mongodb.internal.connection.ProtocolHelper.getCommandFailureException(ProtocolHelper.java:198)at com.mongodb.internal.connection.InternalStreamConnection.receiveCommandMessageResponse(InternalStreamConnection.java:418)at com.mongodb.internal.connection.InternalStreamConnection.sendAndReceive(InternalStreamConnection.java:342)at com.mongodb.internal.connection.CommandHelper.sendAndReceive(CommandHelper.java:96)at com.mongodb.internal.connection.CommandHelper.executeCommand(CommandHelper.java:44)at com.mongodb.internal.connection.SaslAuthenticator.sendSaslStart(SaslAuthenticator.java:228)at com.mongodb.internal.connection.SaslAuthenticator.getNextSaslResponse(SaslAuthenticator.java:135)... 71 more

继续找下办法看怎么处理。

参考:org.springframework.data.mongodb.UncategorizedMongoDbException: Exception authenticating MongoCreden-CSDN博客

问题解决了,能正常保存了。

application.yml文件内容如下:

server:port: 8081servlet.context-path: /#配置数据源
spring:datasource:druid:db-type: com.alibaba.druid.pool.DruidDataSourcedriverClassName: net.sf.log4jdbc.sql.jdbcapi.DriverSpyurl: jdbc:log4jdbc:mysql://${DB_HOST:localhost}:${DB_PORT:3306}/${DB_NAME:eladmin}?serverTimezone=Asia/Shanghai&characterEncoding=utf8&useSSL=falseusername: ${DB_USER:root}password: ${DB_PWD:密码保密}redis:host: localhostport: 6379password: hemingdatabase: 10data:mongodb:host: 43.138.0.199port: 27017username: hmblogspassword: 密码保密database: hmblogsauthentication-database: admines:host: 43.138.0.199port: 9200scheme: http

console截图如下:

在Robo 3T里面查看数据,有对应数据,集合不存在也自动创建了。

执行findUserByUserName(),根据查询条件查看单个数据:

修改数据,执行updateUser()方法,

在Robo 3T中查看数据,如下所示:

删除数据,

 

查看数据,还是保留了id为2的数据。要删id为2的数据,则参数改成2

然后查看数据,该集合已经变成空的了。

用添加数据的方法执行5条数据后,分页查询数据以及根据查询条件分页查询数据,对数据排序,如下:

大于&&排序:

public List<UserEntity> findUserByCriteria(UserEntity user) {Query query=new Query(Criteria.where("id").gt(user.getId()));List<UserEntity> users =  mongoTemplate.find(query , UserEntity.class);users.sort(new Comparator<UserEntity>() {@Overridepublic int compare(UserEntity o1, UserEntity o2) {return o1.getId().intValue()-o2.getId().intValue();}});return users;}

结果如下:

只查出了id>2的数据,且按id升序排序。

下面再看看,根据查询条件分页查询数据,id大于2,且查出第2页数据,每页2条记录,那就查出id=5和id=7的记录,同时要查出总数,便于页面分页。对分页之后得到的结果排序意义不大。

执行结果如下:

现贴出有新增和修改的代码,

新增了PageQuery代码如下:

package com.hmblogs.backend.dao;import lombok.Data;@Data
public class PageQuery<T> {private int pageNum;private int pageSize;private T criteria;
}

新增了PageResult代码如下:

package com.hmblogs.backend.dao;import lombok.Data;import java.util.List;@Data
public class PageResult<T> {private long totalRecord;private List<T> list;
}

UserDao类追加代码如下:

package com.hmblogs.backend.dao;import com.hmblogs.backend.entity.UserEntity;public interface UserDao {public void saveUser(UserEntity user);public UserEntity findUserByUserName(String userName);public void updateUser(UserEntity user);public void deleteUserById(Long id);public PageResult<UserEntity> findUserByCriteria(PageQuery<UserEntity> pageQuery);}

UserDaoImpl类追加代码如下,import块有改动,所以贴出该类的代码:

package com.hmblogs.backend.dao;import com.hmblogs.backend.entity.UserEntity;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.stereotype.Component;import java.util.Comparator;
import java.util.List;@Component
public class UserDaoImpl implements UserDao {@Autowiredprivate MongoTemplate mongoTemplate;/*** 创建对象* @param user*/@Overridepublic void saveUser(UserEntity user) {mongoTemplate.save(user);}/*** 根据用户名查询对象* @param userName* @return*/@Overridepublic UserEntity findUserByUserName(String userName) {Query query=new Query(Criteria.where("userName").is(userName));UserEntity user =  mongoTemplate.findOne(query , UserEntity.class);return user;}/*** 更新对象* @param user*/@Overridepublic void updateUser(UserEntity user) {Query query=new Query(Criteria.where("id").is(user.getId()));Update update= new Update().set("userName", user.getUserName()).set("passWord", user.getPassWord());//更新查询返回结果集的第一条mongoTemplate.updateFirst(query,update,UserEntity.class);//更新查询返回结果集的所有// mongoTemplate.updateMulti(query,update,UserEntity.class);}/*** 删除对象* @param id*/@Overridepublic void deleteUserById(Long id) {Query query=new Query(Criteria.where("id").is(id));mongoTemplate.remove(query,UserEntity.class);}@Overridepublic PageResult<UserEntity> findUserByCriteria(PageQuery<UserEntity> pageQuery) {int pageNum = pageQuery.getPageNum();int pageSize = pageQuery.getPageSize();UserEntity userEntityQuery = pageQuery.getCriteria();Query query = new Query(Criteria.where("id").gt(userEntityQuery.getId()));long count = mongoTemplate.count(query, UserEntity.class);Query queryList = query.skip((pageNum-1)*pageSize).limit(pageSize);List<UserEntity> users =  mongoTemplate.find(queryList , UserEntity.class);PageResult<UserEntity> pageResult = new PageResult<UserEntity>();pageResult.setList(users);pageResult.setTotalRecord(count);return pageResult;}
}

UserDaoTest代码如下:

package com.hmblogs.backend.util;import com.hmblogs.backend.dao.PageQuery;
import com.hmblogs.backend.dao.PageResult;
import com.hmblogs.backend.dao.UserDao;
import com.hmblogs.backend.entity.UserEntity;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;import java.util.List;@RunWith(SpringRunner.class)
@SpringBootTest
public class UserDaoTest {@Autowiredprivate UserDao userDao;@Testpublic void testSaveUser() throws Exception {UserEntity user=new UserEntity();user.setId(4l);user.setUserName("aa");user.setPassWord("bb");userDao.saveUser(user);}@Testpublic void findUserByUserName(){UserEntity user= userDao.findUserByUserName("小明");System.out.println("user is "+user);}@Testpublic void updateUser(){UserEntity user=new UserEntity();user.setId(2l);user.setUserName("天空");user.setPassWord("fffxxxx");userDao.updateUser(user);}@Testpublic void deleteUserById(){userDao.deleteUserById(2l);}@Testpublic void findUsersByCriteria(){UserEntity userQuery = new UserEntity();userQuery.setId(2l);PageQuery<UserEntity> pageQuery = new PageQuery<UserEntity>();pageQuery.setCriteria(userQuery);pageQuery.setPageNum(2);pageQuery.setPageSize(2);PageResult<UserEntity> user= userDao.findUserByCriteria(pageQuery);System.out.println("user is "+user);}
}

根据查询条件筛选数据、分页、查出符合查询条件的总数,都做到了,如果还要再加上要根据最后修改时间降序排序,最后修改的数据要放在第1页,很早之前修改的数据放在最后一页,这里可以理解为根据id降序排序,id值越大的说明越晚产生的,那就是查出id为3、4的记录了,而不是id为5、7的记录。

数据以及需求如下图所示:

但是mongoTemplate的API,没看到有sort的API,怎么办呢?搜资料发现,如下代码可以实现:

public PageResult<UserEntity> findUserByCriteria(PageQuery<UserEntity> pageQuery) {int pageNum = pageQuery.getPageNum();int pageSize = pageQuery.getPageSize();UserEntity userEntityQuery = pageQuery.getCriteria();Query query = new Query(Criteria.where("id").gt(userEntityQuery.getId()));long count = mongoTemplate.count(query, UserEntity.class);// 10. 分页// 11. 排序query.with(PageRequest.of(pageNum-1, pageSize,Sort.by(Sort.Order.desc("id"))));List<UserEntity> users =  mongoTemplate.find(query , UserEntity.class);PageResult<UserEntity> pageResult = new PageResult<UserEntity>();pageResult.setList(users);pageResult.setTotalRecord(count);return pageResult;}

执行结果如下:

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.hqwc.cn/news/449048.html

如若内容造成侵权/违法违规/事实不符,请联系编程知识网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

MATLAB绘制电磁场

MATLAB绘制电磁场举例: clc;close all;clear all;warning off;%清除变量 rand(seed, 100); randn(seed, 100); format long g; m12 for k1:m for j1:m if k1 V(j,k)1; elseif((j1)|(jm)|(km)) V(j,k)0; else …

【MySQL】深入理解隔离性

深入理解隔离性 一、数据库并发的场景二、多版本并发控制&#xff08; MVCC &#xff09;三、三个前提知识1、3个记录隐藏字段2、undo日志 四、快照的概念五、Read View六、隔离级别RR与RC的本质区别 一、数据库并发的场景 数据库并发的场景总共有三种&#xff1a; 读-读&…

PPT录屏功能在哪?一键快速找到它!

在现代办公环境中&#xff0c;ppt的录屏功能日益受到关注&#xff0c;它不仅能帮助我们记录演示文稿的播放过程&#xff0c;还能将操作过程、游戏等内容完美录制下来。可是很多人不知道ppt录屏功能在哪&#xff0c;本文将为您介绍ppt录屏的打开方法&#xff0c;以帮助读者更好地…

C++迷宫游戏详解

个人主页&#xff1a;[PingdiGuo_guo] 收录专栏&#xff1a;[C干货专栏] 大家好呀&#xff0c;我是PingdiGuo_guo&#xff0c;今天我们来学习用C实现一个迷宫游戏。 目录 1.迷宫的具体步骤 1.1.迷宫的初始化 ​编辑 1.2.寻路算法 1.DFS算法 2.BFS算法 1.3.移动 2.总结…

将http转为https访问需要费用吗

首先&#xff0c;需要了解http和https的概念的区别。 http本身是一种超文本传输协议&#xff0c;目前是互联网在进行数据访问过程中最广泛运用的一种网络协议&#xff0c;http工作于客户端与服务器端之间。浏览器作为http客户端通过URL向http服务器端发送所有请求。Web服务器则…

【MongoDB】跨库跨表查询(python版)

MongoDB跨表跨库查询 1.数据准备&#xff1a;2.跨集合查询3.跨库查询应该怎么做&#xff1f; 讲一个简单的例子&#xff0c;python连接mongodb做跨表跨库查询的正确姿势 1.数据准备&#xff1a; use order_db; db.createCollection("orders"); db.orders.insertMany…

jupyter notebook找不到自己创建的环境 无法识别 解决方法

问题描述&#xff1a; 这是最近遇到的一个关于Anaconda的小问题。 用conda创建一个名为 pytorch 的环境想学习pytorch&#xff0c;安装完一切之后在 jupyter 中找不到 pytorch 这个虚拟环境&#xff0c;与之相关的库也都无法调用 解决方法&#xff1a; 实际上是由于在虚拟环境…

【技术策划,游戏设计的新风口】

*** 技术策划&#xff0c;游戏设计的新风口 移动互联网的发展催生了游戏产业对技术策划人才的旺盛需求。最近&#xff0c;一家知名游戏公司发布技术策划招聘&#xff0c;提供35-45k的高薪聘用&#xff0c;充分展现该岗位的紧俏和吸引力。 高薪不仅带来可观的物质回报&#xff…

Blender 使用Rigify绑定做动画导入Unity的问题

导入到Unity的问题&#xff1a; 1.有多余的骨骼&#xff08;非形变骨&#xff09; 2.层级错误 这两个问题是一个问题&#xff1a; 1.第一个问题是因为有形变骨是非形变骨的子骨骼导致的&#xff0c;所以只需要把形变骨放到对应的父级形变骨下即可&#xff0c;CtrlP即可 2.第二…

亚马逊新店铺视频怎么上传?视频验证失败怎么办?——站斧浏览器

亚马逊新店铺视频怎么上传&#xff1f; 登录亚马逊卖家中心&#xff1a;首先&#xff0c;卖家需要登录亚马逊卖家中心。在登录后&#xff0c;可以点击左侧导航栏上的“库存”选项&#xff0c;然后选择“新增或管理商品”。 选择商品&#xff1a;接下来&#xff0c;在“新增或…

同城外卖跑腿app开发:重新定义城市生活

随着科技的发展和人们生活节奏的加快&#xff0c;同城外卖跑腿app应运而生&#xff0c;成为现代城市生活中的重要组成部分。本文将探讨同城外卖跑腿app开发的意义、市场需求、功能特点以及未来的发展趋势。 一、同城外卖跑腿app开发的意义 同城外卖跑腿app作为一种便捷的生活…

Java和JavaScript的区别和联系

大家好&#xff0c;今天给大家介绍Java和JavaScript的区别和联系&#xff0c;文章末尾附有分享大家一个资料包&#xff0c;差不多150多G。里面学习内容、面经、项目都比较新也比较全&#xff01;可进群免费领取。 Java和JavaScript是两种完全不同的编程语言&#xff0c;它们的设…