将实体反射之后获取查询字段的值,并添加到Predicate对象数组中
public Predicate getPredicateAnd(T entity, Root<T> root, CriteriaBuilder cb) throws IntrospectionException , InvocationTargetException, IllegalAccessException { try { //通过反射获取类型 Class<?> c = entity.getClass(); //获取类的字段 Field[] fields = c.getDeclaredFields(); List<Predicate> predicateList = new ArrayList(); for (Field field : fields) { PropertyDescriptor pd = new PropertyDescriptor(field.getName(), c); //获得get方法 Method getMethod = pd.getReadMethod(); //执行get方法返回一个Object Object fieldVal = getMethod.invoke(entity); if (fieldVal != null && !fieldVal.equals(0)) { Path<String> path = root.get(field.getName()); Predicate p = cb.equal(path, fieldVal); predicateList.add(p); } } return cb.and(predicateList.toArray(new Predicate[]{})); } catch (Exception e) { log.error(e.getMessage()); } return null; }
下面是使用方法,因返回类型为Predicate所以直接作为参数传入到CriteriaQuery<?>的where函数中
public T findOne(final T entity) { return getSpecDao().findOne(new Specification<T>() { @Override public Predicate toPredicate(Root<T> root, CriteriaQuery<?> query, CriteriaBuilder cb) { try { query.where( getPredicateAnd(entity, root, cb)); } catch (InvocationTargetException e) { e.printStackTrace(); } catch (IllegalAccessException e) { e.printStackTrace(); } catch (IntrospectionException e) { e.printStackTrace(); } return null; } }); }