我找到了有关如何实现 ajax 服务器端处理的示例。在控制器上,代码如下所示。
@RequestMapping(value = "/persons")
public @ResponseBody
DatatablesResponse<Person> findAllForDataTablesFullSpring(@DatatablesParams DatatablesCriterias criterias) {
DataSet<Person> dataSet = personService.findPersonsWithDatatablesCriterias(criterias);
return DatatablesResponse.build(dataSet, criterias);
}
在服务层
public DataSet<Person> findPersonsWithDatatablesCriterias(DatatablesCriterias criterias) {
List<Person> persons = personRepository.findPersonWithDatatablesCriterias(criterias);
Long count = personRepository.getTotalCount();
Long countFiltered = personRepository.getFilteredCount(criterias);
return new DataSet<Person>(persons, count, countFiltered);
}
在数据访问层
@Override
public List<Person> findPersonWithDatatablesCriterias(DatatablesCriterias criterias) {
StringBuilder queryBuilder = new StringBuilder("SELECT p FROM Person p");
/**
* Step 1: global and individual column filtering
*/
queryBuilder.append(PersonRepositoryUtils.getFilterQuery(criterias));
/**
* Step 2: sorting
*/
if (criterias.hasOneSortedColumn()) {
List<String> orderParams = new ArrayList<String>();
queryBuilder.append(" ORDER BY ");
for (ColumnDef columnDef : criterias.getSortingColumnDefs()) {
orderParams.add("p." + columnDef.getName() + " " + columnDef.getSortDirection());
}
Iterator<String> itr2 = orderParams.iterator();
while (itr2.hasNext()) {
queryBuilder.append(itr2.next());
if (itr2.hasNext()) {
queryBuilder.append(" , ");
}
}
}
TypedQuery<Person> query = entityManager.createQuery(queryBuilder.toString(), Person.class);
/**
* Step 3: paging
*/
query.setFirstResult(criterias.getDisplayStart());
query.setMaxResults(criterias.getDisplaySize());
return query.getResultList();
}
/**
* <p>
* Query used to return the number of filtered persons.
*
* @param criterias
* The DataTables criterias used to filter the persons.
* (maxResult, filtering, paging, ...)
* @return the number of filtered persons.
*/
@Override
public Long getFilteredCount(DatatablesCriterias criterias) {
StringBuilder queryBuilder = new StringBuilder("SELECT p FROM Person p");
queryBuilder.append(PersonRepositoryUtils.getFilterQuery(criterias));
Query query = entityManager.createQuery(queryBuilder.toString());
return Long.parseLong(String.valueOf(query.getResultList().size()));
}
/**
* @return the total count of persons.
*/
@Override
public Long getTotalCount() {
Query query = entityManager.createQuery("SELECT COUNT(p) FROM Person p");
return (Long) query.getSingleResult();
}
我的问题是我需要重复编码数据访问层,这对于我的所有实体都是完全相同的。现在,我想有一个通用的实现。有人可以给我解决这个问题。对于任何使用蒲公英数据表插件的人来说,这将是一个很大的帮助。