One (local sql query, pay attention to what the table name with the name of both the database for a particular database queries)
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); }
Act II (jpa has been achieved paging interface for simple paging query)
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);
Act III (Query notes, hql language bureau for the query specified conditions data)
@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();
Can customize the entire entity (Page <User>), the query may be a few fields (Page <Object []>), and native sql almost the same flexibility.
And France (expansion findAll, suitable for dynamic sql queries)
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 <the User> getUsersPage (PageParam pageParam, NICKNAME String) { // specification defines Specification <the User> = new new Specification Specification <the User> () { / ** * configuration assertion * @param root entity object references * @param query rule query object * @param cb rule to build the object * @return assertion * / @Override public Predicate toPredicate (Root <the User> root, CriteriaQuery <?> query, CriteriaBuilder cb) { List <Predicate> predicates = new ArrayList < > ();// All assertions if (StringUtils.isNotBlank (nickName)) { // add assert the Predicate likeNickName = cb.like (root.get ( "NICKNAME") AS (String.class), NICKNAME + "%."); predicates.add (likeNickName); } return cb.and (predicates.toArray (new new the Predicate [0])); } }; // paging information Pageable pageable = new PageRequest (pageParam.getPage ( ) - 1, pageParam.getLimit ()); // page: Starting from the front end 1, jpa from zero, to be converted // query return this.userRepository.findAll (Specification, Pageable); } }
Five of (use entityManager, suitable for dynamic sql queries)
@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()); } }
}