Java Spring 列表到页面的转换

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/37749559/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-11 19:38:56  来源:igfitidea点击:

Conversion of List to Page in Spring

javaspringlistpaginationspring-data

提问by user3127109

I am trying to convert list to page in spring. I have converted it using

我正在尝试在春季将列表转换为页面。我已经使用

new PageImpl(users, pageable, users.size());

new PageImpl(users, pageable, users.size());

But now I having problem with sorting and pagination itself. When I try passing size and page, the pagination doesn't work.

但是现在我在排序和分页方面遇到了问题。当我尝试传递大小和页面时,分页不起作用。

Here's the code I am using.

这是我正在使用的代码。

My Controller

我的控制器

    public ResponseEntity<User> getUsersByProgramId(
        @RequestParam(name = "programId", required = true) Integer programId Pageable pageable) {

    List<User> users = userService.findAllByProgramId(programId);
    Page<User> pages = new PageImpl<User>(users, pageable, users.size());

    return new ResponseEntity<>(pages, HttpStatus.OK);
}

Here is my user Repo

这是我的用户回购

public interface UserRepo extends JpaRepository<User, Integer>{

public List<User> findAllByProgramId(Integer programId);

Here is my service

这是我的服务

    public List<User> findAllByProgramId(Integer programId);

回答by shilaimuslm

I had the same problem. I used subList:

我有同样的问题。我使用了子列表:

int start = pageable.getOffset();
int end = (start + pageable.getPageSize()) > users.size() ? users.size() : (start + pageable.getPageSize());
Page<User> pages = new PageImpl<User>(users.subList(start, end), pageable, users.size());

回答by dubonzi

As indicated in the reference documentation, Spring Data repositories support pagination on query methods by simply declaring a parameter of type Pageableto make sure they're only reading the data necessary for the requested Page.

正如参考文档中所指出的,Spring Data 存储库通过简单地声明一个 type 参数来支持查询方法的分页,Pageable以确保它们只读取请求的Page.

Page<User> page = findAllByProgramId(Integer programId, Pageable pageable);

That would return a Pageobject with the page size/settings defined in your Pageableobject. No need to get a list and then try to create a page out of it.

这将返回一个具有Page对象中定义的页面大小/设置的Pageable对象。无需获取列表,然后尝试从中创建页面。

回答by ram

Thanks guys below code is working in my case

谢谢下面的代码在我的情况下工作

    int start = pageble.getOffset();
    int end = (start + pageble.getPageSize()) > vehicleModelsList.size() ? vehicleModelsList.size() : (start + pageble.getPageSize());

回答by Borgy Manotoy

Have you tried extending your repository to PagingAndSortingRepository?

您是否尝试将存储库扩展到PagingAndSortingRepository

public interface UserRepo extends PagingAndSortingRepository<Ticket, Integer> {
    Page<User> findAllByProgramId(Integer programId, Pageable pageable);
}

Service

服务

Page<User> findAllByProgramId(Integer programId, Pageable pageable);

I assume you are using interface to the service:

我假设您正在使用该服务的接口:

回答by RBuser2769569

//1) For a boot application create a paging repository interface
public interface PersonRepository extends PagingAndSortingRepository<Person, 
String> {
// Common CURD method are automatically implemented
}
//2) create a service Interface
public interface PersonService {
    Page<Person> listAllByPage(Pageable pageable); // Use common CURD findAll() method
    Page<Object> listSpecByPage(Pageable pageable, String x);

}
//3) create a service Impl Class of service interface
@Service
public class PersonServiceImpl implements PersonService {

    final PersonRepository personRepository;

    @Autowired
    PersonServiceImpl(PersonRepository personRepository){
    this.personRepository = personRepository;
    }

    @Override
    public Page<Person> listAllByPage(Pageable pageable) {
          return personRepository.findAll(pageable);
    }
    @Override
    public Page<Object> listSpecByPage(Pageable pageable, String path) {
        List<Object> objectlist = new ArrayList<Object>();
        // Do your process to get output in a list by using node.js run on a *js file defined in 'path' varriable
        Page<Object> pages1 = new PageImpl<Object>(objectlist, pageable, objectlist.size());
        return pages1;
    }

}
//4) write your controller
public class PersonController {

    final PersonService personService;

    @Autowired
    PersonController( PersonService personService ){
        this.personService = personService;
    }

    @GetMapping("/get") // Use of findALL() function
    Page<Person> listed( Pageable pageable){
        Page<Person> persons = personService.listAllByPage(pageable);
        return persons;
    } 
    @GetMapping("/spec") // Use of defined function
    Page<Object> listSpec( Pageable pageable, String path){
        Page<Object> obj = personService.listSpecByPage(pageable, path);
        return obj;
   } 

}

回答by naveen kumar

Try This:

public Page<Patient> searchPatientPage(SearchPatientDto patient, int page, int size){
        List<Patient> patientsList = new ArrayList<Patient>();
        Set<Patient> list=searchPatient(patient);
        patientsList.addAll(list);
        int start =  new PageRequest(page, size).getOffset();
        int end = (start + new PageRequest(page, size).getPageSize()) > patientsList.size() ? patientsList.size() : (start + new PageRequest(page, size).getPageSize());

        return new PageImpl<Patient>(patientsList.subList(start, end), new PageRequest(page, size), patientsList.size());
    }

回答by Sachin Gaur

There is a Pageimplementationfor that:

有一个Page实现

Page<Something> page = new PageImpl<>(yourList);

回答by Ashish

This could be the solution. Sorting and pagination will work too this way:

这可能是解决方案。排序和分页也可以这样工作:

Controller:

控制器:

public ResponseEntity<User> getUsersByProgramId(
   @RequestParam(name = "programId", required = true) Integer programId Pageable pageable) {
       Page<User> usersPage = userService.findAllByProgramId(programId, pageable);
       Page<User> pages = new PageImpl<User>(usersPage.getContent(), pageable, usersPage.getTotalElements());

       return new ResponseEntity<>(pages, HttpStatus.OK);
}

Service:

服务:

Page<User> findAllByProgramId(Integer programId, Pageable pageable);

Repository:

存储库:

public interface UserRepo extends JpaRepository<User, Integer>{
       public Page<User> findAllByProgramId(Integer programId, Pageable pageable);
}

This way, we can also return different page of entity too.

这样,我们也可以返回不同的实体页面。

回答by Willi Mentzel

You should do it like advised by the dubonzi's answer.

你应该按照 dubonzi's answer 的建议去做。

If you still want to use pagination for a given Listuse PagedListHolder:

如果您仍然想对给定的List使用PagedListHolder使用分页:

List<String> list = // ...

// Creation
PagedListHolder page = new PagedListHolder(list);
page.setPageSize(10); // number of items per page
page.setPage(0);      // set to first page

// Retrieval
page.getPageCount(); // number of pages 
page.getPageList();  // a List which represents the current page

If you need sorting, use another PagedListHolder constructorwith a MutableSortDefinition.

如果您需要排序,请使用另一个带有MutableSortDefinition 的PagedListHolder 构造函数

回答by sreerag

Instead of returing complete array list take subblist as per your requirement. You will get 'offset' and size from 'pageable' object in request body.

根据您的要求,不要返回完整的数组列表,而是使用 subblist。您将从请求正文中的“可分页”对象中获得“偏移量”和大小。

new PageImpl<User>(users.subList(start, end), pageable, users.size());

new PageImpl<User>(users.subList(start, end), pageable, users.size());