經過實體反射實現CriteriaQuery並列條件查詢

將實體反射以後獲取查詢字段的值,並添加到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函數中ide

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;
            }
        });
    }
相關文章
相關標籤/搜索