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.mzph.cn/news/664305.shtml

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

相关文章

奠定基础:用于机器学习的微积分、数学和线性代数

一、说明 机器学习是一个引人入胜的领域&#xff0c;它使计算机能够从数据中学习并做出预测或决策&#xff0c;而无需明确编程。然而&#xff0c;在幕后&#xff0c;有一个坚实的数学和线性代数基础&#xff0c;构成了机器学习算法的支柱。在本文中&#xff0c;我们将探讨在深入…

C++多线程3

生产者消费者模型 OS经典问题&#xff0c;生产者消费者模型,empty和full还有mutex对应到C上如何处理看代码即可 #include <iostream> #include <thread> #include <mutex> #include <condition_variable> #include <queue> using namespace st…

数据中心机房建设的关键痛点及解决方案

随着信息技术的飞速发展&#xff0c;数据中心机房已成为企业信息系统的核心。然而&#xff0c;在机房系统的建设过程中&#xff0c;投资及运行维护成为项目管理的关键痛点。合理的投资决策和高效的运维管理是确保机房系统经济性和可靠性的重要因素。本文将探讨机房系统建设的投…

那些不输于乙游男主人设的国漫男主

最近乙游的势头越来越猛&#xff0c;新宠旧爱一起上阵&#xff0c;叫人应接不暇。在二次元的世界里&#xff0c;乙游男主们凭借着超凡的魅力&#xff0c;成为了无数少女心中的理想对象。他们或冷酷、或温柔、或阳光、或神秘&#xff0c;每一个角色都有着独特的性格和故事。 乙游…

NLP_统计语言模型的发展历程

文章目录 统计语言模型发展的里程碑&#xff1a; 上半部分是语言模型技术的进展&#xff1b;下半部分则是词向量&#xff08;词的表示学习&#xff09;技术的发展。其中&#xff0c;词向量表示的学习为语言模型提供了更高质量的输入信息&#xff08;词向量表示&#xff09; 1…

性能测试常用术语

之前在性能测试过程中&#xff0c;对于某些其中的术语一知半解&#xff0c;导致踩了很多坑。这篇博客&#xff0c;就常见的一些性能测试术语进行一次浅析。。。 负载 对被测系统不断施加压力&#xff0c;直到性能指标超过预期或某项资源使用达到饱和&#xff0c;以验证系统的处…

玩美移动为花西子海外官网打造AR虚拟试妆决方案

全球领先的增强现实&#xff08;AR&#xff09;及人工智能&#xff08;AI&#xff09;美妆科技领导者及玩美系列APP开发商——玩美移动&#xff08;纽交所代码&#xff1a;PERF&#xff09;于近日宣布携手知名美妆品牌花西子&#xff0c;在其线海外官方网页提供多项彩妆虚拟试妆…

C语言搭配EasyX实现贪吃蛇小游戏

封面展示 内部展示 完整代码 #define _CRT_SECURE_NO_WARNINGS #include<easyx.h> #include<stdio.h> #include<mmsystem.h> #pragma comment (lib,"winmm.lib") #define width 40//宽有40个格子 #define height 30//长有40个格子 #define size 2…

ubuntu22.04安装部署02:禁用显卡更新

一、查看可用显卡驱动 ubuntu-drivers devices 二、查看显卡信息 # -i表示不区分大小写 lspci | grep -i nvidia nvidia-smi 三、查看已安装显卡驱动 cat /proc/driver/nvidia/version 四、锁定显卡升级 使用cuda自带额显卡驱动&#xff0c;居然无法&#xff0c;找到如何锁…

TRUNCATE TABLE和DELETE FROM对比

相同点:用于删除数据,同时保留表结构. 不同点: TRUNCATE比DELETE更快(数据量小可能体现不出来,单数据量大就很明显了) 原因:TRUNCATE是DDL(数据定义语言)DELETE是逐行删除属于(DML) TRUNCATE 不会产生大量日志,但DELETE删除会产生大量日志 DELETE FROM 可以加WHERE子句指定…

AI-数学-高中-17-三角函数的定义

原作者视频&#xff1a;三角函数】4三角函数的定义&#xff08;易&#xff09;_哔哩哔哩_bilibili 初中&#xff1a; 高中&#xff1a;三角函数就是单位圆上的点的横纵坐标(x0,y0)。 示例1&#xff1a; 规则&#xff1a; 示例2&#xff1a; 示例3.1&#xff1a; 示例3.2 示例4…

【异常检测复现】【DeSTSeg】在虚拟环境中完成配置

文章目录 1.在虚拟环境中安装git2.更改虚拟环境中包的安装位置3.安装anomalib4.安装虚拟环境5.根据requirements.txt安装包6.选择所建立的虚拟环境&#xff0c;并设置解释器7.查看文件夹的内容8.下载数据集9.引用 记录复现过程中安装各种包的命令 下载数据集到本地 1.在虚拟环境…

(十二)springboot实战——SSE服务推送事件案例实现

前言 SSE&#xff08;Server-Sent Events&#xff0c;服务器推送事件&#xff09;是一种基于HTTP协议的服务器推送技术。它允许服务器向客户端发送异步的、无限长的数据流&#xff0c;而无需客户端不断地轮询或发起请求。这种技术可以用来实现实时通信、在线聊天、即时更新等功…

C++并发编程 -2.线程间共享数据

本章就以在C中进行安全的数据共享为主题。避免上述及其他潜在问题的发生的同时&#xff0c;将共享数据的优势发挥到最大。 一. 锁分类和使用 按照用途分为互斥、递归、读写、自旋、条件变量。本章节着重介绍前四种&#xff0c;条件变量后续章节单独介绍。 由于锁无法进行拷贝…

Day 17------C语言收尾之链表的删除、位运算、预处理、宏定义

链表 空链表&#xff1a; 注意&#xff1a;函数不能返回局部变量的地址 操作&#xff1a; 1.创建空链表 2.头插 3.尾插 4.链表遍历 5.链表的长度 free&#xff1a;释放 删除&#xff1a; 头删 void popFront(struct Node *head) { //1.p指针变量指向首节点 //2.断…

ubuntu22.04 安装部署01:禁用内核更新

一、前言 ubunut22.04系统安装以后&#xff0c;内核更新会导致各种各样的问题&#xff0c;因此锁定初始安装环境特别重要&#xff0c;下面介绍如何锁定内核更新。 二、操作方法 2.1 查看可用内核 dpkg --list | grep linux-image dpkg --list | grep linux-headers dpkg --…

NLP_NLP技术的演进史

文章目录 起源: NLP 的起源可以追溯到阿兰图灵在20 世纪50年代提出的图灵测试。图灵测试的基本思想是&#xff0c;如果一个计算机程序能在自然语言对话中表现得像一个人&#xff0c;那么我们可以说它具有智能。从这里我们可以看出&#xff0c;AI最早的愿景与自然语言处理息息相…

Multisim14.0仿真(四十二)基于74LS183的8位表决器设计

一、74LS183简介&#xff1a; 74LS183是一种4位高速全加器&#xff0c;用于数字电路中的加法运算。74LS183输入端包括两个4位二进制数和一个进位信号&#xff0c;输出端包括1个4位二进制数和一个进位信号。 74LS138具有快速响应、低功耗灯特点&#xff0c;能实现高校的数字匀速…

计算huggingface模型占用硬盘空间的实战代码

大家好,我是herosunly。985院校硕士毕业,现担任算法研究员一职,热衷于机器学习算法研究与应用。曾获得阿里云天池比赛第一名,CCF比赛第二名,科大讯飞比赛第三名。拥有多项发明专利。对机器学习和深度学习拥有自己独到的见解。曾经辅导过若干个非计算机专业的学生进入到算法…

ChatGPT的探索与实践-应用篇

这篇文章主要介绍在实际的开发过程当中&#xff0c;如何使用GPT帮助开发&#xff0c;优化流程&#xff0c;文末会介绍如何与618大促实际的业务相结合&#xff0c;来提升应用价值。全是干货&#xff0c;且本文所有代码和脚本都是利用GPT生成的&#xff0c;请放心食用。 场景一&…