【java】spring-data-jpa 集成hibernate实现多条件分页查询
初次接触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); }