Hibernate动态查询工具类RequestQuery

public class RequestQuery {

    private String parameterName;
    private String compareType;
    private Object value;
    // get set

    public static List buildRequestQuery(HttpServletRequest request)
            throws IllegalAccessException {
        List requestQueryList = new ArrayList<>();
        //获取所有查询参数的键值
        Enumeration enumeration = request.getParameterNames();
        while(enumeration.hasMoreElements()) {
            String queryKey = enumeration.nextElement();
            String value = request.getParameter(queryKey);
            if (queryKey.startsWith("q_") && !"".equals(value) && value != null) {
                //q_productName_like_s
                String[] array = queryKey.split("_");
                if (array == null && array.length != 4) {
                    throw new IllegalAccessException("查询条件异常:" + queryKey);
                }
                RequestQuery query = new RequestQuery();
                query.setParameterName(array[1]);
                query.setCompareType(array[2]);
                query.setValue(transValueType(array[3],value));
                requestQueryList.add(query);
            }
        }
        return requestQueryList;
    }

    //将查询参数的value值进行转化的方法
    private static Object transValueType(String valueType,String value) {
        if ("s".equalsIgnoreCase(valueType)) {
            return value;
        }
        if ("d".equalsIgnoreCase(valueType)) {
            return Double.valueOf(value);
        }
        if("f".equalsIgnoreCase(valueType)) {
            return Float.valueOf(value);
        }
        if("i".equalsIgnoreCase(valueType)) {
            return Integer.valueOf(value);
        }
        if("bd".equalsIgnoreCase(valueType)) {
            return new BigDecimal(value);
        }
        return null;
    }


}

你可能感兴趣的:(Hibernate动态查询工具类RequestQuery)