使用Spring进行排序,过滤和分页

时间:2015-08-06 14:44:40

标签: sorting filtering paging spring-data-jpa restful-url

如何实现分页使用Spring?

一些建议?

public class ClienteServiceImpl implements ClienteService {

public List<Cliente> findAllClientes(final String ragioneSociale, final String partitaIva, String sortBy, String sortOrder, Integer startResult, Integer maxRows) {

    Sort sort = null;
    Specification<Cliente> specification = null;

    if(sortBy != null){
        // sorting
        sort = new Sort(Direction.fromString(sortOrder), sortBy);
    }

    if(ragioneSociale != null || partitaIva != null){
        // filtering
        specification = new Specification<Cliente>() {
            public Predicate toPredicate(Root<Cliente> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
                Predicate p1 =  ragioneSociale != null ? cb.like(root.<String>get("ragioneSociale"), ragioneSociale + "%") : cb.isNotNull(root.<Long>get("id"));
                Predicate p2 =  partitaIva != null ? cb.like(root.<String>get("partitaIva"), partitaIva + "%") : cb.isNotNull(root.<Long>get("id"));
                return cb.and(p1,p2);
            }
        };
    }

    List<Cliente> clientes = new ArrayList<Cliente>();
    if(sort == null && specification == null) clientes = clienteDAO.findAll();
    else if(sort != null && specification == null) clientes = clienteDAO.findAll(sort);
    else if(sort == null && specification != null) clientes = clienteDAO.findAll(specification);
    else if(sort != null && specification != null) clientes = clienteDAO.findAll(specification, sort);



    return clientes;
}

1 个答案:

答案 0 :(得分:3)

使用Pageable作为方法参数,并将参数传递给Repo/DAO方法。它将自动生成在Pageable中的值上分页的分页和排序SQL。下面是代码示例。

public List<Cliente> findAllClientes(final String ragioneSociale, final String partitaIva, Pageable pageable) {
    clienteDAO.findByExample(ragioneSociale, partitaIva, pageable);
}

@Repository
public interface ClienteRepository extends JpaRepository<Cliente, Long> {

    @Query("from Cliente c where c.ragioneSociale=:ragioneSociale AND c.partitaIva=:partitaIva")
    Page<Cliente> findByExample(@Param("ragioneSociale") String ragioneSociale, @Param("partitaIva") String partitaIva, Pageable page);

}

希望这有帮助。