Mongodb

在 MongoRepository 中使用 Skip 和 Limit

1、概览 Spring Data MongoDB 的 MongoRepository 接口提供了一种简单的方式与 MongoDB Collection 进行交互。 本文将带你了解如何在 MongoRepository 中使用 limit 和 skip。 2、初始设置 首先,创建一个名为 StudentRepository 的 Repository,用于存储 Student 信息: public interface StudentRepository extends MongoRepository<Student, String> {} 然后,向该 Repository 添加一些 Student 示例数据: @Before public void setUp() { Student student1 = new Student("A", "Abraham", 15L); Student student2 = new Student("B", "Usman", 30L); Student student3 = new Student("C", "David", 20L); Student student4 = new Student("D", "Tina", 45L); Student student5 = new Student("E", "Maria", 33L); studentList = Arrays.

Spring Security 使用 Mongodb 进行认证

1. Overview Spring Security 提供了不同的身份认证系统,例如通过数据库和 UserDetailService。 有时可能不想使用 JPA 持久层,而是想使用 MongoDB Repository。本文将带你了解如何使用 Spring Security 和 MongoDB 对用户进行认证。 2、Spring Security 使用 MongoDB 进行认证 MongoDB Repository 与 JPA Repository 类似不过,我们需要设置不同的配置。 2.1、Maven 依赖 本文使用嵌入式 MongoDB。首先,添加 spring-boot-starter-data-mongodb 和 de.flapdoodle.embed.mongo 依赖: <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-mongodb</artifactId> </dependency> <dependency> <groupId>de.flapdoodle.embed</groupId> <artifactId>de.flapdoodle.embed.mongo</artifactId> <version>3.3.1</version> </dependency> 2.2、配置 创建配置类: @Configuration public class MongoConfig { private static final String CONNECTION_STRING = "mongodb://%s:%d"; private static final String HOST = "localhost"; @Bean public MongoTemplate mongoTemplate() throws Exception { int randomPort = SocketUtils.

Spring Data MongoDB 开启 Debug 日志

1、概览 在使用 Spring Data MongoDB 时,可能需要比默认级别(INFO)更高的日志,以查看执行语句或查询参数等一些附加信息。 2、配置 MongoDB 查询日志 Spring Data MongoDB 通过 MongoOperations 接口或其主要的实现 MongoTemplate 来访问数据,因此只需为 MongoTemplate 类配置调 Debug 级别的日志即可。 与其他 Spring 或 Java 应用一样,可以使用日志库并为 MongoTemplate 定义日志级别。类似于如下: <logger name="org.springframework.data.mongodb.core.MongoTemplate" level="DEBUG" /> 如果是 Spring Boot 应用,可以直接在 application.properties 文件中进行配置: logging.level.org.springframework.data.mongodb.core.MongoTemplate=DEBUG 同样,也可以使用 YAML 文件: logging: level: org: springframework: data: mongodb: core: MongoTemplate: DEBUG 3、日志测试类 创建一个 Book 类: @Document(collection = "book") public class Book { @MongoId private ObjectId id; private String bookName; private String authorName; // getter 和 setter 方法 } 创建一个简单的测试类用于测试,并查看输出日志。