How to get List from Page in Spring Data REST

Soumitri Pattnaik :

I am using JPARespository for all my CRUD operation. Recently I wanted to implement sorting, so I went ahead with Pagable.

The problem is, I want the repository methods to return List objects, I use them in my service layer.

How can I achieve this, is there a way to convert these Page objects to List?

Sohlowmawn :

If you use pageable in a jpa repository method, spring will always return a Page not a List. I suggest you have a service method that calls the repository method and extracts the contents of the Page result into a list.

So if your repository method is thus:

import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;

@Repository
public interface RecordRepository extends JpaRepository<Record, Integer>{                      
     Page<Record> findAll(Pageable pageable);
}

then you can have a service class which has a method that calls the repository method

@Service
public class RecordService{

   @Autowired
   RecordRepository recordRepository;

  public List<Record> findAll(PageRequest pageRequest){
    Page<Record> recordsPage = recordRepository.findAll(pageRequest);
    return recordsPage.getContent();
  }
}

so in your calling class instead of calling the repository directly you can just use the service. thus:

public class MyRecordImpl{
   @Autowired
  RecordService recordService;

  public void doSomething(){
      int page = 0; int pageSize = 5;
      List<Record> recordList = recordService.findAll(new PageRequest(page, pageSize, new Sort(Sort.Direction.DESC, "recordId")));
     //do other implementations here
   }
}

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=453868&siteId=1