初次接觸spring-data-jpa,實現多條件分頁查詢。
基礎環境 Spring Boot+spring-data-jpa+hibernate+mysql
1.接口
要繼承這個接口,這個接口提供了多條件分頁的方法。
public interface RjAuthuInfoRespository extends JpaRepository<RjAuthInfo,Long>,JpaSpecificationExecutor<RjAuthInfo> { }
2、service 接口和實現
public interface RjAuthService { Page<RjAuthInfo> findAll(Map<String,Object> map); }
@Service public class RjAuthServiceImpl implements RjAuthService { @Autowired private RjAuthuInfoRespository rjPageRepository; @Override public Page<RjAuthInfo> findAll(Map<String,Object> map) { return rjPageRepository.findAll(new Specification<RjAuthInfo>() { Long hotel =(Long)map.get("hotel"); Date start = (Date) map.get("start"); Date end = (Date) map.get("end"); public Predicate toPredicate(Root<RjAuthInfo> root, CriteriaQuery<?> query, CriteriaBuilder cb) { Path<Long> hotelPath = root.get("hotel"); Path<Date> date = root.get("date"); /** * 連接查詢條件, 不定參數,可以連接0..N個查詢條件 */ List<Predicate> predicates = Lists.newArrayList(); if(start!=null){ predicates.add(cb.greaterThan(date,start)); } if(end!=null){ predicates.add(cb.lessThan(date,end)); } if(null != hotel){ predicates.add(cb.equal(hotelPath,hotel)); } query.where(predicates.toArray(new Predicate[predicates.size()])); return null; } }, new PageRequest((int)map.get("page")-1,(int)map.get("size"))); } }
3、控制層實現
封裝自己的條件到service查詢。
/** * 條件查詢認證信息 * @param start 開始時間 * @param end 結束時間 * @param hotel 酒店ID * @param page 當前頁 * @param size 每頁記錄數 * @return */ @RequestMapping(path="getAuthInfo",method ={RequestMethod.GET,RequestMethod.POST}) public @ResponseBody Page<RjAuthInfo> test(@RequestParam(value = "start",required = false)String start,@RequestParam(value = "end",required = false)String end, @RequestParam(value = "hotel",required = false)String hotel,@RequestParam("page")int page,@RequestParam("size")int size){ SimpleDateFormat format=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); Date a= null; Date b=null; Long hotelId=null; try { if(!StringUtils.isEmpty(start)){ a = format.parse(start); } if(!StringUtils.isEmpty(end)){ b = format.parse(end); } if(!StringUtils.isEmpty(hotel)){ hotelId=Long.valueOf(hotel); } } catch (Exception e) { log.error(e.getMessage(),e); return null; } Map<String,Object> map= Maps.newHashMap(); map.put("hotel",hotelId); map.put("start",a); map.put("end",b); map.put("page",page); map.put("size",size); return rjAuthService.findAll(map); }