Mongodb series - use spring-data-mongodb to implement paging query

In the process of developing with the spring-data-mongodb framework, it is necessary to implement paging query, so I searched on Baidu, and I did not find a satisfactory one and googled it again, and found an idea.

In the official documentation of spring-data-mongodb, it is recommended that you use PagingAndSortingRepository  it to implement paging, but I really don't like this design!!

Use the method name to map the query statement, the framework will automatically generate the execution code, and also define a set of syntax for this, for example:

 
 

public interface UserRepository extends MongoRepository<User, String>, QueryDslPredicateExecutor<User> {
@Query("{ 'name' : ?0 }")
List<User> findUsersByName(String name);

 
 

@Query("{ 'age' : { $gt: ?0, $lt: ?1 } }")
List<User> findUsersByAgeBetween(int ageGT, int ageLT);

 
 

List<User> findByName(String name);

 
 

List<User> findByNameLikeOrderByAgeAsc(String name);

 
 

List<User> findByAgeBetween(int ageGT, int ageLT);

 
 

@Query(value = "{}", fields = "{name : 1}")
List<User> findNameAndId();

 
 

@Query(value = "{}", fields = "{_id : 0}")
List<User> findNameAndAgeExcludeId();
}

This interface class only defines the interface, and does not need to be implemented, because the SDM framework (spring-data-mongodb for short, the abbreviation is used below) will generate code for you.

findByAgeBetween(int ageGT, int ageLT);-> 就是where ageGT <age and age <ageLT;

It may feel simple at first, but once there are more fields, the query conditions become more complicated! You don't know what you are writing at all! When others see a long list of method names in your code, they are also directly confused..

And many of the paging queries found are also directly used by PagingAndSortingRepository  this interface, which is automatically generated... I don't like it very much... Just check how to use MongoTemplate to implement...

Get off work first.... come back from vacation to make up.. haha

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325057985&siteId=291194637