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

最新文章

  1. SQL Left Join, Right Join, Inner Join, and Natural Join 各种Join小结
  2. 易语言5.6 精简破解版[Ctoo]
  3. sharepoint:找不到位于 http://XX.XX.XX.XX 的 Web
  4. Qt使用一个事件队列对所有发出的事件进行维护(QObject的event()函数相当于dispatch函数),用EventLabel 继承QLabel作为例子(简单明了) good
  5. Java学习笔记--反射
  6. 一个实例明白AutoResetEvent和 ManulResetEvent的用法
  7. 转载:执行脚本出现bin/bash: bad interpreter: No such file or directory
  8. el简略说明与11个隐含对象
  9. ASP.NET的Application简介1
  10. 5.中文问题(自身,操作系统级别,应用软件的本身),mysql数据库备份
  11. Win7怎样禁用自带IE浏览器
  12. CSS position: absolute、relative定位问题详解
  13. c语言基础学习05
  14. history.pushState()和history.replaceState()
  15. Ubuntu12.04 LTS 32位 安装ns-2.35
  16. Tinker热修复
  17. 单用户实例添加DB账号
  18. router-link 自定义点击事件
  19. python模块之collections random
  20. Java精选面试题之Spring Boot 三十三问

热门文章

  1. 使用js 文件参数 以及IHttpModule实现服务验证asp.net 版的初步实现
  2. leetcode -day28 Unique Binary Search Trees I II
  3. C# 中的应用配置
  4. Oracle更换字符集
  5. selenium常用获取元素点
  6. AppBox Mvc数据库初始化
  7. bzoj2464 小明的游戏
  8. [转]Windows 注册自定义的协议
  9. 【转载】Keepalived安装使用详解
  10. Linux 期中架构 PHP