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);
} }

法五(使用entityManager,适用于动态sql查询)

@Service
@Transactional
public class IncomeService{ /**
* 实体管理对象
*/
@PersistenceContext
EntityManager entityManager; public Page<IncomeDaily> findIncomeDailysByPage(PageParam pageParam, String cpId, String appId, Date start, Date end, String sp) {
StringBuilder countSelectSql = new StringBuilder();
countSelectSql.append("select count(*) from IncomeDaily po where 1=1 "); StringBuilder selectSql = new StringBuilder();
selectSql.append("from IncomeDaily po where 1=1 "); Map<String,Object> params = new HashMap<>();
StringBuilder whereSql = new StringBuilder();
if(StringUtils.isNotBlank(cpId)){
whereSql.append(" and cpId=:cpId ");
params.put("cpId",cpId);
}
if(StringUtils.isNotBlank(appId)){
whereSql.append(" and appId=:appId ");
params.put("appId",appId);
}
if(StringUtils.isNotBlank(sp)){
whereSql.append(" and sp=:sp ");
params.put("sp",sp);
}
if (start == null)
{
start = DateUtil.getStartOfDate(new Date());
}
whereSql.append(" and po.bizDate >= :startTime");
params.put("startTime", start); if (end != null)
{
whereSql.append(" and po.bizDate <= :endTime");
params.put("endTime", end);
} String countSql = new StringBuilder().append(countSelectSql).append(whereSql).toString();
Query countQuery = this.entityManager.createQuery(countSql,Long.class);
this.setParameters(countQuery,params);
Long count = (Long) countQuery.getSingleResult(); String querySql = new StringBuilder().append(selectSql).append(whereSql).toString();
Query query = this.entityManager.createQuery(querySql,IncomeDaily.class);
this.setParameters(query,params);
if(pageParam != null){ //分页
query.setFirstResult(pageParam.getStart());
query.setMaxResults(pageParam.getLength());
} List<IncomeDaily> incomeDailyList = query.getResultList();
if(pageParam != null) { //分页
Pageable pageable = new PageRequest(pageParam.getPage(), pageParam.getLength());
Page<IncomeDaily> incomeDailyPage = new PageImpl<IncomeDaily>(incomeDailyList, pageable, count);
return incomeDailyPage;
}else{ //不分页
return new PageImpl<IncomeDaily>(incomeDailyList);
}
} /**
* 给hql参数设置值
* @param query 查询
* @param params 参数
*/
private void setParameters(Query query,Map<String,Object> params){
for(Map.Entry<String,Object> entry:params.entrySet()){
query.setParameter(entry.getKey(),entry.getValue());
}
}
}

jpa分页的更多相关文章
- spring data jpa 分页查询
https://www.cnblogs.com/hdwang/p/7843405.html spring data jpa 分页查询 法一(本地sql查询,注意表名啥的都用数据库中的名称,适用于特 ...
- SpringBoot Jpa 分页查询最新配置方式
这是已经被废弃的接口 Sort sort = new Sort(Sort.Direction.DESC,"bean类中字段"); //创建时间降序排序 Pageable pagea ...
- Spring Boot JPA分页 PageRequest报错
在使用Spring Boot JPA分页 PageRequest分页时,出现如下错误: 本来以为是包导入出现了问题,结果发现并不是.导入包如下: 后来在网上查找相关资料,发现这样的用法,好像也可以用, ...
- JPA 分页处理
1.要实现jpa分页管理首先得要正确配置jpa环境,在spring环境中的配置如下: 开启注解功能 <bean class="org.springframework.orm.jpa.s ...
- spring data jpa分页5种方法
7.12.12 分页 本地sql查询 注意表名啥的都用数据库中的名称, 适用于特定数据库的查询 public interface UserRepository extends JpaRepositor ...
- JPA分页查询与条件分页查询
情有独钟的JPA 平时在写一些小项目时,比较喜欢引用 Spring Data Jpa,其实还是图他写代码快~在日常的开发工作中,分页列表查询基本是随处可见,下面一起看一下如何使用 jpa 进行多条件查 ...
- SpringBoot JPA + 分页 + 单元测试SpringBoot JPA条件查询
application.properties 新增数据库链接必须的参数 spring.jpa.properties.hibernate.hbm2ddl.auto=update 表示会自动更新表结构,所 ...
- Spring data Jpa 分页从1开始,查询方法兼容 Mybatis,分页参数兼容Jqgrid
废话少说 有参数可以设置 在org.springframework.boot.autoconfigure.data.web.SpringDataWebProperties 中 /** * Whethe ...
- springBoot jpa 分页
1.jap中有自带的分页方法 在dao层中使用 Page<LinkUrl> findAll(Pageable pageable); 2.在controller层 public List&l ...
随机推荐
- Python 从入门到进阶之路(一)
人生苦短,我用 Python. Python 无疑是目前最火的语言之一,在这里就不再夸他的 NB 之处了,本着对计算机编程的浓厚兴趣,便开始了对 Python 的自学之路,并记录下此学习记录的心酸历程 ...
- 一起学Android之ContentProvider
本文主要讲解在Android开发中ContentProvider的常规用法,仅供学习分享使用,如有不足之处,还请指正. 访问一个ContentProvider 在Android开发中,应用程序通过Co ...
- pecl安装和卸载示例
比如安装MongoDB扩展 命令行下输入: [#] /usr/local/php/bin/pecl install mongodb ......嗒吧嗒吧一大堆输出后 Build process com ...
- Flask 教程 第五章:用户登录
本文翻译自The Flask Mega-Tutorial Part V: User Logins 这是Flask Mega-Tutorial系列的第五部分,我将告诉你如何创建一个用户登录子系统. 你在 ...
- GIT命令行统计代码提交行数
项目中遇到写报告的时候要反馈某个人或者某个功能的代码量,又没有集成CI这些插件,可以简单的用GIT命令统计下代码提交量: --统计某个人的提交代码 git log --author="old ...
- MySQL基础之数据管理【4】
外键约束的使用(只有InnoDB存储引擎支持外键) create table news_cate( id tinyint unsigned auto_increment key comment '编号 ...
- LeetCode刷题191119
博主渣渣一枚,刷刷leetcode给自己瞅瞅,大神们由更好方法还望不吝赐教.题目及解法来自于力扣(LeetCode),传送门. 算法: 给定一个非负整数数组,你最初位于数组的第一个位置. 数组中的每个 ...
- 010.MongoDB备份恢复
一 MongoDB备份 1.1 备份概述 mongodb数据备份和还原主要分为二种,一种是针对于库的mongodump和mongorestore,一种是针对库中表的mongoexport和mongoi ...
- 利用Mac的功能键|如何在Mac上使用F键
Mac键盘的顶部是一组按键,这些按键的特征是F后跟1-12数字.这些键称为Mac功能键,使您可以通过按几个键来更改某些设置并快速访问Mac功能. 如果您是Mac的所有者,是时候学习这些键各自可以做什么 ...
- python连接MySQL pymysql模块,游标,SQL注入问题,增删改查操作
pymysql模块 pymysql是用python控制终端对MySQL数据库进行操作的第三方模块 import pymysql # 1.连接数据库 client = pymysql.connect( ...