How to implement Kendo Grid pagination and sorting with Spring Data.
Setup Kendo grid options as below in controller or directive
$scope.publishHistoryGridOptions = {
columns: [
{field: "email", title: "Publisher"},
{field: "status", title: "Status"},
{field: "failure", title: "Failure"},
{field: "success", title: "Success"},
{field: "duplicate", title: "Duplicate"}
],
sortable: true,
pageable: true,
filterable: true,
dataSource: new kendo.data.DataSource({
page: 0,
pageSize: 15,
serverPaging: true,
serverFiltering: true,
serverSorting: true,
transport: {
read: {
url: "mailing-api/lists/history/" + $scope.listId,
dataType: "json",
type: "GET"
},
parameterMap: function (data) {
// Mapping between Spring data pagination and kendo UI pagination parameters
// Pagination
var serverUrlParams = {
// pagination
size: data.pageSize,
page: data.page = data.page - 1// as Spring page starts from 0
};
// Sorting
if (data.sort && data.sort.length > 0)
serverUrlParams.sort = data.sort[0].field + ',' + data.sort[0].dir;
return serverUrlParams;
}
},
change: function (e) {
$scope.gridData = this.data();
},
schema: {
data: "content",
total: "totalElements"
}
})
};
The key part here is the parameterMap
using which you can translates Kendo Grid query parameters to Spring Data ones.
parameterMap: function (data) {
// Mapping between Spring data pagination and kendo UI pagination
return {
size: data.pageSize,
page: data.page = data.page-1 // as Spring page starts from 0
};
}
The schema
tells Kendo Grid which response JSON attribute contains the total
count and the dataset.
schema: {
data: "content",
total: "totalElements"
}
Controller:
@RequestMapping(value = "/history/{listId}")
public Page<ListPublish> getPublishHistory(@PathVariable("listId") long listId,
Pageable pageRequest) {
return publishingService.getListHistory(listId, pageRequest);
}
Service:
@Override
public Page<ListPublish> getListHistory(long listId, Pageable pageRequest) {
return listPublishRepository.findByMailingListId(listId, pageRequest);
}
Repository:
public interface ListPublishRepository extends CrudRepository<ListPublish, Long>,
PagingAndSortingRepository<ListPublish, Long> {
Page<ListPublish> findByMailingListId(long listId, Pageable pageRequest);
}