SpringBoot integrates Jpa to sort, paginate, conditionally query and filter data

I introduced the simple use of SpringBoot integrated Jpa before, and then I will introduce the use of Jpa to connect to the database to sort, paginate, conditional query and filter operations on data. First create a Springboot project and have inherited JPA dependencies, (https://www.cnblogs.com/eternality/p/17391141.html)

1. Sorting query

Sort through the Sort class of the findAll method, and sort according to the entity class fields. Descending descending order, ascending ascending order, the default is ascending ascending order if not filled.
List<User> mapperAll = userMapper.findAll(Sort.by("id").descending()); 
mapperAll.forEach(System.out::println);
search result:

Sort.by() is a variable parameter, which can pass in one or more values.
//Sort by status first, then sort by ID 
List<User> statusAll = userMapper.findAll(Sort.by("status","id").descending()); 
statusAll.forEach(System.out: :println);

Set the first property in descending order and the second property in ascending order
 Sort sort = Sort.by("status").descending().and(Sort.by("id").ascending());
 List<User> diffOb= userMapper.findAll(sort);
 diffOb.forEach(System.out::println);

If the field information passed in does not exist in the entity class, the code access will report an error. like:
 
 
List<User> exceptionAll = userMapper.findAll(Sort.by("en_name").descending());
exceptionAll.forEach(System.out::println);
 
 

   An exception will be reported that the field information cannot be found:

org.springframework.data.mapping.PropertyReferenceException: No property en found for type User! Did you mean 'id'?

2. Paging query

JPA provides us with a paging method, and we can view the relationship diagram of the interface-integrated JpaRepository interface. Found that there is a PagingAndSortingRepository interface.

 Click on the interface to view:

 Use this interface method to implement pagination query. We found that this method needs to pass in a Pageable, click Pageable to view and find that it is also an interface, we click to view its implementation class.

Pagination can be realized by using the PageRequest class. PageRequest has a static of method, the page parameter is to display the current page number, and the size is to display how much data is currently displayed.
//第一页,显示4条数据  0为一页 1为二页  输入页数大于总页数则输出内容为空
        PageRequest request = PageRequest.of(0, 4); 
        Page<User> userPage = userMapper.findAll(request);
        System.out.println();
        System.out.println("总页数: "+userPage.getTotalPages()); //总页数
        System.out.println("总条数: "+userPage.getTotalElements()); //总条数
        System.out.println("查询的数据: "+userPage.getContent());//查询的数据
        System.out.println("显示条数: "+userPage.getSize()); //显示条数
        System.out.println("当前页数: "+Integer.valueOf(Integer.valueOf(userPage.getNumber())+1)); //当前页数

The query result is:

You can also sort the paging query, sorting in descending order according to the primary key
        PageRequest pageRequest = PageRequest.of(0, 4, Sort.by("id").descending()); 
        Page<User> orderPAge = userMapper.findAll(pageRequest); 
        System.out.println("Query data: " +orderPAge.getContent());//Query data 
        orderPAge.getContent().forEach(System.out::println);
Pagination to sort multiple fields in the same sort
 
 
        PageRequest pageRequest1 = PageRequest.of(0, 4, Sort.Direction.DESC, "status","id"); 
        Page<User> orde = userMapper.findAll(pageRequest1); 
        System.out.println("Query data: "+orde.getContent());//Query data 
        orde.getContent().forEach(System.out::println);
Pagination for different sorting of multiple fields According to status ascending order, id descending order
 
 
        PageRequest of = PageRequest.of(0, 4, Sort.by("status").ascending().and(Sort.by("id").descending()));
        Page<User> ord = userMapper.findAll(of);
        ord.getContent().forEach(System.out::println);
 
 

View query output sql results:

3. Condition query

Let's look at conditional query using JPA. In JPA, JPA uses the findBy method to customize the query. You can also use findAllBy. There is no difference between these two. In fact, finBy... is used for querying.
//Query according to the account name, put back the data if there is information, and return null if there is no query, if you query multiple pieces of data, an error will be reported 
        User user=userMapper.findByAccount("hibernateTest"); 
//Dao layer
       User findByAccount(String account);

  If you query multiple items, an error javax.persistence.NonUniqueResultException: query did not return a unique result: 4 will be reported. Change the receiving parameter to List, and you can query multiple items of data.

 
 
 List<User> findByAccount(String account);
 
 

 FindBy can also support multiple keywords for query:

And: equivalent to the and keyword in SQL, findByAccountAndPassword(String account, String password); 
And: equivalent to the and keyword in SQL, findByAccountAndPassword(String account, String password); 
Or: equivalent to SQL in or keyword, findByAccountOrName(String account, String name); 
Between: equivalent to the between keyword in SQL, findByIdBetween(int min, int max); 
LessThan: equivalent to "<" in SQL, findByIdLessThan(int id ); 
GreaterThan: equivalent to ">" in SQL, findByIdGreaterThan(int id); 
IsNull: equivalent to "is null" in SQL, findByNameIsNull(); 
IsNotNull: equivalent to "is not null" in SQL , findByNameIsNotNull(); NotNull: Equivalent to IsNotNull; 
Like: Equivalent to "like" in SQL, findByNameLike(String name); In this way, you need to add %name% to pass the value, you can use Containing, this method will be on both sides of the string Both add %, 
in addition to StartingWith and EndingWith, respectively?%, %?
NotLike: Equivalent to "not like" in SQL, findByNameNotLike(String name); %name% needs to be added to pass the value 
Not: Equivalent to "!=" in SQL, findByUsernameNot(String user); 
OrderBy: Equivalent to "order by" in SQL, findByNameOrderByStatusAsc(String name); 
In: equivalent to "in" in SQL, findByIdIn(Collection userIdList), the parameters of the method can be Collection type, array or variable length parameters; 
NotIn : Equivalent to "not in" in SQL, findByNameNotIn(Collection userList), the parameter of the method can be Collection type, or an array or variable length parameter; here is an introduction to the use of fuzzy query 
:
List<User> userList2=userMapper.findByNameLike("%hibernateTest%");
userList2.forEach(System.out::println);
List<User> userList3=userMapper.findByNameContaining("hibernateTest");
userList3.forEach(System.out::println);//dao层
List<User> findByNameLike(String name);List<User> findByNameContaining(String name);

After the introduction of the above findBy rules is completed, then we combine the above paging and sorting to query the filtered data. Condition + pagination + sort query use:
Page<User> userPage = userMapper.findByNameLike("%hibernateJPa%", PageRequest.of(0, 2, Sort.by("id").descending()));
        System.out.println("总页数: "+userPage.getTotalPages()); //总页数
        System.out.println("总条数: "+userPage.getTotalElements()); //总条数
        System.out.println("查询的数据: "+userPage.getContent());//查询的数据
        System.out.println("显示条数: "+userPage.getSize()); //显示条数
        System.out.println("当前页数: "+Integer.valueOf(Integer.valueOf(userPage.getNumber())+1)); //当前页数//dao层
Page<User> findByNameLike(String name, Pageable pageable);
 
 

   search result:

We have finished the introduction of querying, sorting and paging using JPA. There are complex sql conditional queries behind JPA, which need to inherit the JpaSpecificationExecutor interface. There are not many JpaSpecificationExecutor interface methods but they are easy to use. It is recommended that you have time to learn it.

Guess you like

Origin blog.csdn.net/xxxzzzqqq_/article/details/130654357