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
?
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
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With