7.12.12	分页
本地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); @Query(value = "SELECT u FROM Users u WHERE u.username like %:username%")
List<User> findByName(@Param("username") String username);
} 使用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());
}
}
} 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几乎一样灵活。 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); 扩充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);
}
}

spring data jpa分页5种方法的更多相关文章

  1. spring data jpa 分页查询

    https://www.cnblogs.com/hdwang/p/7843405.html spring data jpa 分页查询   法一(本地sql查询,注意表名啥的都用数据库中的名称,适用于特 ...

  2. Spring Data JPA 简单查询--接口方法

    一.接口方法整理速查 下表针对于简单查询,即JpaRepository接口(继承了CrudRepository接口.PagingAndSortingRepository接口)中的可访问方法进行整理.( ...

  3. Spring Data Jpa的四种查询方式

    一.调用接口的方式 1.基本介绍 通过调用接口里的方法查询,需要我们自定义的接口继承Spring Data Jpa规定的接口 public interface UserDao extends JpaR ...

  4. Spring Data JPA简单查询接口方法速查

    下表针对于简单查询,即JpaRepository接口(继承了CrudRepository接口.PagingAndSortingRepository接口)中的可访问方法进行整理.(1)先按照功能进行分类 ...

  5. Spring data Jpa 分页从1开始,查询方法兼容 Mybatis,分页参数兼容Jqgrid

    废话少说 有参数可以设置 在org.springframework.boot.autoconfigure.data.web.SpringDataWebProperties 中 /** * Whethe ...

  6. Spring Data Jpa (三)定义查询方法

    本章详细讲解如何利用方法名定义查询方法(Defining Query Methods) (1)定义查询方法的配置方法 由于Spring JPA Repository的实现原理是采用动态代理的机制,所以 ...

  7. Spring Data JPA,一种动态条件查询的写法

    我们在使用SpringData JPA框架时,进行条件查询,如果是固定条件的查询,我们可以使用符合框架规则的自定义方法以及@Query注解实现. 如果是查询条件是动态的,框架也提供了查询接口. Jpa ...

  8. spring集成JPA的三种方法配置

    JPA是Java EE5规范之一,是一个orm规范,由厂商来实现该规范.目前有hibernate,OpenJPA,TopLink和EclipseJPA等实现 spring提供三种方法集成JPA:1.L ...

  9. spring boot系列(四)spring boot 配置spring data jpa (保存修改删除方法)

    spring boot 使用jpa在pom.xml在上文中已经介绍过.在这里直接介绍各个类文件如何编写: 代码结构: domain(存放实体类文件): repository(存放数据库操作文件,相当于 ...

随机推荐

  1. LeetCode Factorial Trailing Zeroes Python

    Factorial Trailing Zeroes Given an integer n, return the number of trailing zeroes in n!. 题目意思: n求阶乘 ...

  2. MySQL--常见ALTER TABLE 操作

    ##================================## ## 修改表的存储引擎 ## SHOW TABLE STATUS LIKE 'TB_001' \G; ALTER TABLE ...

  3. 寻找高边电流IC

    因为项目需要,无法使用地的电流检测,需要使用高边的电流检测 IC. 搜索的关键字: 高边 电流 高侧 电流 目前找到以下几款: INA199A1,来自参考方案,属于宽电压输入的. INA180B4ID ...

  4. greasemonkey修改网页url

    // ==UserScript== // @name JSHE_ModifyFunction // @namespace jshe // @include http://localhost/* // ...

  5. mac上安装nginx

    终端执行: brew install nginx nginx 默认安装在 /usr/local/Cellar/nginx/1.12.2 conf 文件默认安装在 /usr/local/etc/ngin ...

  6. Python+VSCode+Git 学习总结

    稍等,先写个脑图... 继续,读完本文,你会学会: 1.如何在VSCode中写Python代码: 2.如何在VSCode中使用Git: 为什么写这篇总结 首先,我假设你是一名Python语言初学者,你 ...

  7. 【python】copy浅拷贝和deepcopy深拷贝

    Python中的对象之间赋值时是按引用传递的,如果需要拷贝对象,需要使用标准库中的copy模块. 1. copy.copy 浅拷贝 只拷贝父对象,不会拷贝对象的内部的子对象. 2. copy.deep ...

  8. 一小时入门webpack

    webpack现在已经成为了大众化的项目必要脚手架,基本上现在的很多项目都需要webpack,由于webpack的出现glup和grunt已经完败,今天我们来说一下webpack如何使用. 首先我们需 ...

  9. bzoj1033 杀蚂蚁

    假设游戏中的蚂蚁也是按这个规则选择路线: 1.每一秒钟开始的时候,蚂蚁都在平面中的某个整点上.如果蚂蚁没有扛着蛋糕,它会在该点留下2单位的信息素,否则它会留下5单位的信息素.然后蚂蚁会在正北.正南.正 ...

  10. python学习笔记--pycurl模块安装遇到的问题。

    1.用easy_install安装的时候 [root@idayuan ~]# easy_install pycurl Searching for pycurl Best match: pycurl A ...