技术控

    今日:70| 主题:49409
收藏本版 (1)
最新软件应用技术尽在掌握

[其他] Spring Data (Part 5): Paging and Sorting

[复制链接]
暧昧害死人 发表于 2016-10-14 13:17:56
84 0

立即注册CoLaBug.com会员,免费获得投稿人的专业资料,享用更多功能,玩转个人品牌!

您需要 登录 才可以下载或查看,没有帐号?立即注册

x
Overview  

  When we perform bulk operations, like finding all "Person"s from the database or finding everyone based on a country, we often do the paging so that we can present a small data chunk to the end user and, in the next request, we fetch the next data chunk. By doing this, we see two main advantages.
  Advantages  

  This method enhances readability for end users. If we show everything on a page, then it will be long enough to need a scrollbar. The users will need to scroll to find a particular person, which is bad UI design.
  It also reduces the query time and enhances performance as, in spite of fetching all the data, we only fetch a small chunk of data — amounting to less query time. A lot of UI technology supports client-side paging, which fetches all the data, and, based on the request, shows paginated data. But that doesn't reduce the query time, it only provides the first advantage.
  Disadvantages  

  To request every data chunk, a server trip is required. You can optimize it through caching, but when an end user is in the process of fetching data, another Person can be added to the system. If that situation, it might show as the last entry of one page and the first entry of another.
  But we are always using paging to fetch a small chunk of data, rather than all of it.
  Spring Data and Pagination  

  Spring Data provides support for pagination. It creates all the logic to implement paging, like a count for the rows for all the pages and more.
  Implementing paging is very easy in Spring Data. We just need to follow the steps below:
  
       
  •       In your custom repository, extend        PagingAndSortingRepository.      
       
  •         Create a          PageRequestobject, which is an implementation of the           Pageableinterface        
            This PageRequest object takes the page number, the page size, and sorts direction and sort field.
       
  • By passing requested page number and page limit you can get the data for this page.      
    If you pass a wrong page number Spring data will take care of that and not return any data.  
  Paging Code Implementation  

  1. Create a repository that extends PagingAndSortingRepository.
  1. package com.example.repo;
  2. import java.util.List;
  3. import org.springframework.data.jpa.repository.Query;
  4. import org.springframework.data.querydsl.QueryDslPredicateExecutor;
  5. import org.springframework.data.repository.CrudRepository;
  6. import org.springframework.data.repository.PagingAndSortingRepository;
  7. import org.springframework.stereotype.Repository;
  8. import com.example.person.Person;
  9. @Repository
  10. public interface PersonRepositary extends PagingAndSortingRepository<Person, Long>,QueryDslPredicateExecutor<Person> {
  11.     @Query("select p from Person p where p.country like ?1 order by country")
  12.     List<Person> findByCountryContains(String country);
  13.     List<Person> findPersonByHobbyName(String name);
  14.     @Query("select p from Person p where p.id = ?1 and  country='America'")
  15.     Person findOne(Long id);
  16. }
复制代码
2.    Create domain objects.  
  1. package com.example.person;
  2. import java.util.ArrayList;
  3. import java.util.List;
  4. import javax.persistence.CascadeType;
  5. import javax.persistence.Entity;
  6. import javax.persistence.FetchType;
  7. import javax.persistence.GeneratedValue;
  8. import javax.persistence.GenerationType;
  9. import javax.persistence.Id;
  10. import javax.persistence.OneToMany;
  11. @Entity
  12. public class Person {
  13.     @Id
  14.     @GeneratedValue(strategy=GenerationType.AUTO)
  15.     private Long id;
  16.     private String name;
  17.     private String country;
  18.     private String gender;
  19. @OneToMany(mappedBy="person",targetEntity=Hobby.class,
  20.        fetch=FetchType.EAGER,cascade=CascadeType.ALL)
  21.         List<Hobby> hobby;
  22. public String getName() {
  23.     return name;
  24. }
  25. public void setName(String name) {
  26.     this.name = name;
  27. }
  28. public String getCountry() {
  29.     return country;
  30. }
  31. public void setCountry(String country) {
  32.     this.country = country;
  33. }
  34. public String getGender() {
  35.     return gender;
  36. }
  37. public void setGender(String gender) {
  38.     this.gender = gender;
  39. }
  40. public Long getId() {
  41.     return id;
  42. }
  43. public void setId(Long id) {
  44.     this.id = id;
  45. }
  46. public List<Hobby> getHobby() {
  47.     return hobby;
  48. }
  49. public void setHobby(List<Hobby> hobby) {
  50.     this.hobby = hobby;
  51. }
  52. public void addHobby(Hobby ihobby)
  53. {
  54.     if(hobby == null)
  55.     {
  56.         hobby = new ArrayList<Hobby>();
  57.     }
  58.     hobby.add(ihobby);
  59. }
  60.     @Override
  61.     public String toString() {
  62.         return "Person [id=" + id + ", name=" + name + ", country=" + country + ", gender=" + gender + "]";
  63.     }
  64. }
复制代码
3. Fetch all Persons. Create a PageRequest Object with a limit of 1 and requesting for the first page.
  1. package com.example.person;
  2. import java.util.List;
  3. import org.slf4j.Logger;
  4. import org.slf4j.LoggerFactory;
  5. import org.springframework.beans.factory.annotation.Autowired;
  6. import org.springframework.boot.CommandLineRunner;
  7. import org.springframework.boot.SpringApplication;
  8. import org.springframework.boot.autoconfigure.SpringBootApplication;
  9. import org.springframework.context.annotation.Bean;
  10. import org.springframework.data.domain.PageRequest;
  11. import org.springframework.data.domain.Sort;
  12. import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
  13. import com.example.repo.HobbyRepository;
  14. import com.example.repo.PersonRepositary;
  15. import com.querydsl.core.types.dsl.BooleanExpression;
  16. @SpringBootApplication
  17. @EnableJpaRepositories("com.example.repo")
  18. public class PersonApplication {
  19.     @Autowired
  20.     HobbyRepository hRepo;
  21.     private static final Logger log = LoggerFactory.getLogger(PersonApplication.class);
  22.     @Bean
  23.     public CommandLineRunner demo(PersonRepositary repository) {
  24.         findAll(repository);
  25.         return null;
  26.     }
  27.     private PageRequest gotoPage(int page)
  28.     {
  29.         PageRequest request = new PageRequest(page,1)
  30.         return request;
  31.     }
  32.     private void findAll(PersonRepositary repository)
  33.     {
  34.         Iterable<Person> pList = repository.findAll(gotoPage(0));
  35.         for(Person p : pList)
  36.         log.info("Person " + p);
  37.     }
  38.     public static void main(String[] args) {
  39.         SpringApplication.run(PersonApplication.class, args);
  40.     }
  41. }
复制代码
Output  

  1. Hibernate:
  2.     select
  3.         count(person0_.id) as col_0_0_
  4.     from
  5.         person person0_
  6. Hibernate:
  7.     select
  8.         person0_.id as id1_1_,
  9.         person0_.country as country2_1_,
  10.         person0_.gender as gender3_1_,
  11.         person0_.name as name4_1_
  12.     from
  13.         person person0_ limit ?
  14. Person Person [id=13, name=Samir mitra, country=America, gender=male]
复制代码
Paging and Sorting Code Implementation  

    To do the sorting, we have to pass the sort direction and sorting fields along with the page number and limit. Suppose we want to sort by country name in ascending order — we modify the goto
    method like so:
   
  1. private PageRequest gotoPage(int page)
  2. {
  3.     PageRequest request = new PageRequest(page,1,Sort.Direction.ASC,"country");
  4.     return request;
  5. }
复制代码
Output  

  1. select
  2.         count(person0_.id) as col_0_0_
  3.     from
  4.         person person0_
  5. Hibernate:
  6.     select
  7.         person0_.id as id1_1_,
  8.         person0_.country as country2_1_,
  9.         person0_.gender as gender3_1_,
  10.         person0_.name as name4_1_
  11.     from
  12.         person person0_
  13.     order by
  14.         person0_.country asc limit ?
复制代码
Here we pass the ascending order and country property. And there you have it! This should help you get your data sorted and organized just how you want it.
友荐云推荐




上一篇:Top list of Software Development Life Cycle Risks | David Tzemach
下一篇:Program development by stepwise refinement
酷辣虫提示酷辣虫禁止发表任何与中华人民共和国法律有抵触的内容!所有内容由用户发布,并不代表酷辣虫的观点,酷辣虫无法对用户发布内容真实性提供任何的保证,请自行验证并承担风险与后果。如您有版权、违规等问题,请通过"联系我们"或"违规举报"告知我们处理。

*滑动验证:
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

我要投稿

推荐阅读

扫码访问 @iTTTTT瑞翔 的微博
回页顶回复上一篇下一篇回列表手机版
手机版/CoLaBug.com ( 粤ICP备05003221号 | 文网文[2010]257号 )|网站地图 酷辣虫

© 2001-2016 Comsenz Inc. Design: Dean. DiscuzFans.

返回顶部 返回列表