• spring data jpa 分页查询(小结)


    原文:https://www.cnblogs.com/hdwang/p/7843405.html

    spring data jpa 分页查询

    方法一(本地sql查询,注意表名啥的都用数据库中的名称,适用于特定数据库的查询)

    public interface UserRepository extends JpaRepository<User, Long> {
    
      @Query(value = "SELECT * FROM USERS WHERE LASTNAME = ?1",
        countQuery = "SELECT count(*) FROM USERS WHERE LASTNAME = ?1",
        nativeQuery = true)
      Page<User> findByLastname(String lastname, Pageable pageable);
    }

    方法二(jpa已经实现的分页接口,适用于简单的分页查询)

    public interface PagingAndSortingRepository<T, ID extends Serializable>
      extends CrudRepository<T, ID> {
    
      Iterable<T> findAll(Sort sort);
    
      Page<T> findAll(Pageable pageable);
    }
    
    Accessing the second page of User by a page size of 20 you could simply do something like this:
    
    PagingAndSortingRepository<User, Long> repository = // … get access to a bean
    Page<User> users = repository.findAll(new PageRequest(1, 20));
    User findFirstByOrderByLastnameAsc();
    
    User findTopByOrderByAgeDesc();
    
    Page<User> queryFirst10ByLastname(String lastname, Pageable pageable);
    
    Slice<User> findTop3ByLastname(String lastname, Pageable pageable);
    
    List<User> findFirst10ByLastname(String lastname, Sort sort);
    
    List<User> findTop10ByLastname(String lastname, Pageable pageable);
    //service
     Sort sort = new Sort(Sort.Direction.DESC,"createTime"); //创建时间降序排序
     Pageable pageable = new PageRequest(pageNumber,pageSize,sort);
     this.depositRecordRepository.findAllByUserIdIn(userIds,pageable);
    
    //repository
    Page<DepositRecord> findAllByUserIdIn(List<Long> userIds,Pageable pageable);

    方法三(Query注解,hql语局,适用于查询指定条件的数据)

     @Query(value = "select b.roomUid from RoomBoard b where b.userId=:userId and b.lastBoard=true order by  b.createTime desc")
        Page<String> findRoomUidsByUserIdPageable(@Param("userId") long userId, Pageable pageable);
    Pageable pageable = new PageRequest(pageNumber,pageSize);
    Page<String> page = this.roomBoardRepository.findRoomUidsByUserIdPageable(userId,pageable);
    List<String> roomUids = page.getContent();

    可以自定义整个实体(Page<User>),也可以查询某几个字段(Page<Object[]>),和原生sql几乎一样灵活。

    方法四(扩充findAll,适用于动态sql查询)

    public interface UserRepository extends JpaRepository<User, Long> {
    
        Page<User> findAll(Specification<User> spec, Pageable pageable);
    } 
    @Service
    public class UserService {
    
        @Autowired
        private UserRepository userRepository;
    
        public Page<User> getUsersPage(PageParam pageParam, String nickName) {
            //规格定义
            Specification<User> specification = new Specification<User>() {
    
                /**
                 * 构造断言
                 * @param root 实体对象引用
                 * @param query 规则查询对象
                 * @param cb 规则构建对象
                 * @return 断言
                 */
                @Override
                public Predicate toPredicate(Root<User> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
                    List<Predicate> predicates = new ArrayList<>(); //所有的断言
                    if(StringUtils.isNotBlank(nickName)){ //添加断言
                        Predicate likeNickName = cb.like(root.get("nickName").as(String.class),nickName+"%");
                        predicates.add(likeNickName);
                    }
                    return cb.and(predicates.toArray(new Predicate[0]));
                }
            };
            //分页信息
            Pageable pageable = new PageRequest(pageParam.getPage()-1,pageParam.getLimit()); //页码:前端从1开始,jpa从0开始,做个转换
            //查询
            return this.userRepository.findAll(specification,pageable);
        }
    
    }
  • 相关阅读:
    intel 蓝牙驱动安装时报错
    H310C,B365,M.2 NVME SSD,USB3.0,安装 WIN7 64 位
    C# .NET 判断输入的字符串是否只包含数字和英文字母
    squid http,https, 代理,默认端口3128
    C# .net mvc web api 返回 json 内容,过滤值为null的属性
    centos7安装python-3.5
    systemctl命令完全指南
    Centos7中systemctl命令详解
    Python if 和 for 的多种写法
    CentOS 7.0,启用iptables防火墙
  • 原文地址:https://www.cnblogs.com/lshan/p/12970706.html
Copyright © 2020-2023  润新知