jpa多條件查詢


首先繼承JpaSpecificationExecutor<T>接口

需要用到JpaSpecificationExecutor<T>中的Page<T> findAll(@Nullable Specification<T> spec, Pageable pageable);//多條件分頁查詢

 

ITpSamplerInfoService.java

Page<TpSamplerInfo> findByConditionPage(Long samplerCode,String crossName,Pageable pageable);

TpSamplerInfoServiceImpl.java實現類

@Autowired
ITpSamplerInfoDao samplerInfoDao;//繼承JpaSpecificationExecutor<T>


@Override public Page<TpSamplerInfo> findByConditionPage(Long samplerCode,String crossName, Pageable pageable) { Page<TpSamplerInfo> pageList = samplerInfoDao.findAll(new Specification<TpSamplerInfo>() { @Override public Predicate toPredicate(Root<TpSamplerInfo> root, CriteriaQuery<?> query, CriteriaBuilder criteriaBuilder) { List<Predicate> list = new ArrayList<Predicate>(); if(samplerCode!=null) { list.add(criteriaBuilder.like(root.get("samplerCode"), "%"+samplerCode+"%")); } if(crossName!=null) { //外鍵對象的屬性,要用join再get list.add(criteriaBuilder.like(root.join("tpCrossroadInfo").get("crssroadName"), crossName)); } Predicate[] array = new Predicate[list.size()]; return criteriaBuilder.and(list.toArray(array)); } },pageable); return pageList; }
//例子2,查詢時間段內的記錄
@Override
	public Page<MapPack> findAll(Integer code, String startData, String endData, Pageable pageable) {
		Page<MapPack> pageList = getMapPackDao().findAll(new Specification<MapPack>() {
			
			@Override
			public Predicate toPredicate(Root<MapPack> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
				List<Predicate> list = new ArrayList<Predicate>();
				
				SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
				SimpleDateFormat sdfmat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
				
				if (StringUtils.isNotEmpty(startData) && StringUtils.isNotEmpty(endData)) {
			        try {
						list.add(cb.between(root.get("registerTime"),
								sdfmat.parse(sdfmat.format(sdf.parse(startData).getTime())),
	                            sdfmat.parse(sdfmat.format(sdf.parse(endData).getTime() + 86400000))));
					} catch (ParseException e) {
						e.printStackTrace();
					}
			    }
				if(code!=-1) {
					list.add(cb.equal(root.join("city").get("id").as(String.class), code));
				}
				Predicate[] array = new Predicate[list.size()];
                return cb.and(list.toArray(array));
			}
		}, pageable);
		return pageList;
	}

  

  

 controller

@RequestMapping("/getAllSamplerInfo")
    public Map<String,Object> findByConditionPage(@RequestParam("pageNumber") int page,@RequestParam("pageSize") int size,
            @RequestParam("samplerCode") Long samplerCode,@RequestParam("crossName") String crossName){
        Map<String,Object> map = new HashMap<String, Object>();
        Pageable pageable = PageRequest.of(page-1, size, Direction.DESC, "id");
        Page<TpSamplerInfo> pageList = tpSamplerInfoService.findByConditionPage(samplerCode,crossName, pageable);
        //使用值對象Vo包裝一下實體類,解決遞歸問題
        List<TpSamplerInfoVo> list = new ArrayList<>();
        pageList.forEach(pl->{
            TpSamplerInfoVo tpVo = new TpSamplerInfoVo(pl);
            list.add(tpVo);
        });
        map.put("rows", list);
        map.put("total", pageList.getTotalElements());
        
        return map;
        
    }

 注意:在多條件查詢時候查詢id主鍵的時候遇到過一個錯誤

Parameter value [%3%] did not match expected type [java.lang.Long (n/a)]      意思是參數不匹配預期類型,id是Long類型

解決辦法:list.add(criteriaBuilder.like(root.get("id").as(String.class), "%"+crossId+"%"));

加上as(String.class)就不會出現類型不匹配的問題

 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM