软件编程
位置:首页>> 软件编程>> java编程>> Java简单高效实现分页功能

Java简单高效实现分页功能

作者:程序零世界  发布时间:2022-05-24 13:56:02 

标签:Java,分页,功能

今天想说的就是能够在我们操作数据库的时候更简单的更高效的实现,现成的CRUD接口直接调用,方便快捷,不用再写复杂的sql,带吗简单易懂,话不多说上方法

1、Utils.java工具类中的方法


/** 2 * 获取Sort
 *
 * @param direction - 排序方向
 * @param column - 用于排序的字段
 */
public static Sort getSort(String direction,String column){
  Sort sort = null;
  if(column == null || column == "") return null;
  if(direction.equals("asc")||direction.equals("ASC")){
    sort = Sort.by(Sort.Direction.ASC,column);
  }else {
    sort = Sort.by(Sort.Direction.DESC,column);
  }
  return sort;
}
/**
* 获取分页
* @param pageNumber 当前页
* @param pageSize 页面大小
* @param sort 排序;sort为空则不排序只分页
* @return 分页对象
*/
public static Pageable getPageable(int pageNumber,int pageSize,Sort sort){
 if(sort!=null){
   return PageRequest.of(pageNumber,pageSize,sort);
 }
   return PageRequest.of(pageNumber,pageSize);
}
/**
  * 判断String是否为空
  * @param str
  * @return
  */
  private static boolean isEmpty(String str){
    if(str.equals(null)||str.equals("")) return true;
    return false;
  }

2、实现类

这里查询相关参数是前端传的,所以用默认值了,查询条件可以是多条件动态,排序也可以是动态的,只要传排序字段和排序方向对号入座即可。


@Override
public Page<User> findAll() {
 // 创建测试对象
 User user = new User();
 user.setName("1");
 Sort sort = Utils.getSort("asc","name");
 Pageable pageable = Utils.getPageable(0,5,sort);
 // 调用组装查询条件方法
 Specification<User> spec = getSpecification(user);
 return userRepository.findAll(spec,pageable);
}

/**
* 组装查询条件
* @param user -查询相关对象
* @return 返回组装过的多查询条件
*/
private Specification<User> getSpecification(User user) {
 Specification<User> specification = new Specification<User>() {
   @Override
   public Predicate toPredicate(Root<User> root, CriteriaQuery<?> criteriaQuery, CriteriaBuilder criteriaBuilder) {
     List<Predicate> predicates = new ArrayList<>();
     // 判断条件不为空
     if(!Utils.isEmpty(user.getName())){
       predicates.add(criteriaBuilder.like(root.get("name"),user.getName()));
     }
     return criteriaQuery.where(predicates.toArray(new Predicate[predicates.size()])).getRestriction();
   }
 };
 return specification;
}

3.repository类中这么写

@Repository
public interface UserRepository extends JpaRepository<User, Integer>, JpaSpecificationExecutor<User> {}

来源:https://www.cnblogs.com/MonsterJ/p/13567857.html

0
投稿

猜你喜欢

手机版 软件编程 asp之家 www.aspxhome.com