下面就来详细讲解“SpringMVC应用Mongodb分页实现”的完整攻略。
一、引入依赖
我们首先需要在项目中引入Mongodb和Spring Data Mongodb的依赖:
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-mongodb</artifactId>
<version>2.2.6.RELEASE</version>
</dependency>
<dependency>
<groupId>org.mongodb</groupId>
<artifactId>mongo-java-driver</artifactId>
<version>3.11.1</version>
</dependency>
二、创建实体类
我们需要创建一个实体类,用来和MongoDB数据库中的集合进行映射。比如,我们创建一个User类:
public class User {
private String id;
private String name;
private int age;
// 省略getter和setter方法...
}
三、定义Repository
我们需要定义一个Repository接口,用来进行CRUD操作。比如,我们创建一个UserRepository接口:
public interface UserRepository extends MongoRepository<User, String> {
Page<User> findByName(String name, Pageable pageable);
}
在这个接口中,我们定义了一个findByName方法,该方法用于根据name字段进行查询,并且支持分页。其中,Pageable是Spring Data提供的用于封装分页信息的类,它包含了当前页码、每页大小、排序规则等信息。
四、实现Service
我们通过定义一个Service类来调用Repository接口中定义的方法。例如:
@Service
public class UserService {
@Autowired
private UserRepository userRepository;
public Page<User> findUserByName(String name, int pageNum, int pageSize) {
PageRequest pageRequest = PageRequest.of(pageNum, pageSize);
return userRepository.findByName(name, pageRequest);
}
}
上述代码中,我们通过PageRequest创建了一个分页请求对象,然后调用了UserRepository中定义的findByName方法进行查询。
五、创建Controller
最后,我们创建一个Controller类来处理用户请求,并返回数据。例如:
@RequestMapping("/users")
@RestController
public class UserController {
@Autowired
private UserService userService;
@GetMapping
public Page<User> findUserByName(@RequestParam("name") String name,
@RequestParam("pageNum") int pageNum,
@RequestParam("pageSize") int pageSize) {
return userService.findUserByName(name, pageNum, pageSize);
}
}
上述代码中,我们将请求参数name、pageNum和pageSize传递给了UserService中的findUserByName方法进行查询,并返回了查询结果Page
至此,我们已经完成了“SpringMVC应用MongoDB分页实现”的攻略。如果你想获取更多关于SpringMVC和MongoDB的知识,可以参考以下两个示例:
示例一
创建MongoDB数据库配置类
@Configuration
public class MongoConfig extends AbstractMongoClientConfiguration {
@Override
protected String getDatabaseName() {
return "test";
}
@Override
public MongoClient mongoClient() {
ConnectionString connectionString = new ConnectionString("mongodb://localhost:27017/test");
MongoClientSettings mongoClientSettings = MongoClientSettings.builder()
.applyConnectionString(connectionString)
.build();
return MongoClients.create(mongoClientSettings);
}
}
编写实体类
@Data
@NoArgsConstructor
@AllArgsConstructor
@Document(collection = "user")
public class User {
@Id
private String id;
private String name;
private int age;
}
编写Repository接口
@Repository
public interface UserRepository extends MongoRepository<User, String> {
Page<User> findByName(String name, Pageable pageable);
}
编写Service类
@Service
public class UserService {
@Autowired
private UserRepository userRepository;
public Page<User> findUserByName(String name, int pageNum, int pageSize) {
PageRequest pageRequest = PageRequest.of(pageNum, pageSize);
return userRepository.findByName(name, pageRequest);
}
}
编写Controller类
@RestController
@RequestMapping("/user")
public class UserController {
@Autowired
private UserService userService;
/**
* 根据姓名查询用户列表
* @param name 姓名
* @param pageNum 页码
* @param pageSize 页面大小
* @return 分页查询结果
*/
@GetMapping("/list")
public ResultResponse<Page<User>> queryList(@RequestParam String name,
@RequestParam int pageNum,
@RequestParam int pageSize) {
Page<User> page = userService.findUserByName(name, pageNum, pageSize);
return ResultResponse.success(page);
}
}
示例二
创建MongoDB数据库配置类
@Configuration
@EnableMongoRepositories(basePackages = "io.github.pak3nuh.mg.dao")
public class MongoConfiguration extends AbstractMongoClientConfiguration {
@Value("${spring.data.mongodb.uri}")
private String mongoUri;
@Override
protected String getDatabaseName() {
return "pet_store";
}
@Override
public MongoClient mongoClient() {
return MongoClients.create(mongoUri);
}
}
编写实体类
@Data
@NoArgsConstructor
@AllArgsConstructor
@Document("pets_data")
public class Pet {
@Id
private String id;
@Indexed
private String species;
@Indexed
private String breed;
private String name;
private LocalDate birthDate;
private List<String> medicalProblems;
private String reservedBy;
}
编写Repository接口
@Repository
public interface PetRepository extends PagingAndSortingRepository<Pet, String> {
Page<Pet> findByBreed(final String breed, final Pageable pageable);
Pet findByReservedBy(final String reservationHandle);
}
编写Service类
@Service
public class PetService {
@Autowired
private PetRepository petRepository;
public Page<Pet> findPetsByBreed(final String breed, final int pageNumber, final int pageSize) {
PageRequest pageRequest = PageRequest.of(pageNumber, pageSize);
return petRepository.findByBreed(breed, pageRequest);
}
public Pet reserve(final String petId, final String reservationHandle) {
Optional<Pet> optional = petRepository.findById(petId);
if (!optional.isPresent()) {
throw new RuntimeException("Could not find pet: " + petId);
}
final Pet pet = optional.get();
if (StringUtils.hasText(pet.getReservedBy())) {
throw new RuntimeException("Pet is already reserved for " + pet.getReservedBy());
}
pet.setReservedBy(reservationHandle);
return petRepository.save(pet);
}
public void cancelReservation(final String petId, final String cancellationHandle) {
Optional<Pet> optional = petRepository.findById(petId);
if (!optional.isPresent()) {
throw new RuntimeException("Could not find pet: " + petId);
}
final Pet pet = optional.get();
if (cancellationHandle.equals(pet.getReservedBy())) {
pet.setReservedBy(null);
petRepository.save(pet);
} else {
throw new RuntimeException("Can only cancel reservation for pet made by the handler, "
+ pet.getReservedBy() + " , but request coming from the handler " + cancellationHandle);
}
}
}
编写Controller类
@RestController
@RequestMapping("/pets")
public class PetController {
@Autowired
private PetService petService;
@GetMapping
public ResponseEntity<?> findPetsByBreed(@RequestParam final String breed,
@RequestParam final int pageNumber,
@RequestParam final int pageSize) {
return ResponseEntity.ok(
petService.findPetsByBreed(breed, pageNumber, pageSize)
);
}
@PutMapping("/{id}/reservation")
public ResponseEntity<?> reservePet(@PathVariable final String id,
@RequestParam final String handler) {
final Pet pet = petService.reserve(id, handler);
return ResponseEntity.ok(pet);
}
@PutMapping("/{id}/cancellation")
public ResponseEntity<?> cancelPetReservation(@PathVariable final String id,
@RequestParam final String handler) {
petService.cancelReservation(id, handler);
return ResponseEntity.ok(null);
}
}
以上就是关于“SpringMVC应用MongoDB分页实现”的攻略和两条示例的详细介绍。希望对你有所帮助!
本站文章如无特殊说明,均为本站原创,如若转载,请注明出处:Springmvc应用Mongodb分页实现 - Python技术站