fengxiang
2018-08-17 4967f0b4fe4a3ddc1b30d0c08a1b031189b09cc3
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
package com.moral.common.util;
 
import com.moral.common.bean.Constants;
import com.moral.common.bean.PageBean;
import lombok.extern.log4j.Log4j;
import tk.mybatis.mapper.entity.Example;
 
import java.io.UnsupportedEncodingException;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
 
@Log4j
public class ExampleUtil {
    private final static String SPLIT = "\\|";
    private final static String OR = "_OR";
    private final static String OR_SPLIT = OR+SPLIT;
    private final static String CRITERIA = "_CR";
    private final static String CRITERIA_SPLIT = CRITERIA+SPLIT;
    private final static String CONDITION = "_CO";
    private final static String CONDITION_SPLIT = CONDITION+SPLIT;
    private static Map<String, Method> criteriaMethodMap = new ConcurrentHashMap<>();
    private static void setOrderByClause(Example example,String orderByClause) throws UnsupportedEncodingException, NoSuchFieldException {
           orderByClause = URLDecoder.decode(orderByClause,"UTF-8");
           String[] orderBys = orderByClause.split(CRITERIA_SPLIT);
           for(String orderBy : orderBys){
               String[] items = orderBy.split(CONDITION_SPLIT);
               if(items.length == 2){
                   String property = items[0];
                   String sort = items[1];
                   if(isPropertyOfClass(example.getEntityClass(),property)){
 
                       if("asc".equals(sort)){
                           example.orderBy(property).asc();
                       }else{
                           example.orderBy(property).desc();
                       }
                   }
               }
           }
    }
    public static Example generateExample(Class clazz, PageBean page){
        return  generateExample(clazz,false,page);
    }
    public static Example generateExample(Class clazz, boolean isDelete, PageBean page) {
        Example example = null;
        try {
            String params = page.getQueryParams();
            String orderByClause = page.getOrderByClause();
            example = new Example(clazz);
            if(!StringUtils.isNullOrEmpty(orderByClause)){
                setOrderByClause(example,orderByClause);
            }
            if(!StringUtils.isNullOrEmpty(params)){
                params = URLDecoder.decode(params, "UTF-8");
                if (params.startsWith(OR)) {
                    String[] criteria = params.trim().split(OR_SPLIT);
                    for (String criterion : criteria) {
                        // criterion为null或""跳过
                        if(StringUtils.isNullOrEmpty(criterion)) { continue;};
                        Example.Criteria criteriaOfExample = example.or();
                        if (!StringUtils.isNullOrEmpty(criterion)) {
                            String[] conditions = criterion.trim().split(CRITERIA_SPLIT);
                            for (String condition : conditions) {
                                if (!StringUtils.isNullOrEmpty(condition)) {
                                    String[] conditionItems = condition.split(CONDITION_SPLIT);
                                    if (conditionItems != null && conditionItems.length > 1) {
                                        //方法名
                                        String methodName = conditionItems[0];
                                        //属性名
                                        String propertyName = conditionItems[1];
                                        //参数列表
                                        List values = new ArrayList<Object>();
                                        if (conditionItems.length > 2) {
                                            for (int index = 2; index < conditionItems.length; index++) {
                                                values.add(conditionItems[index]);
                                            }
                                        }
                                        Method method = getExampleMethod(methodName,values.size()+1);
                                        if (method != null && (methodName.equals("andCondition")||isPropertyOfClass(clazz, propertyName))) {
                                            invokeMethod(criteriaOfExample,method,propertyName,values);
                                        }
 
                                    }
                                }
                            }
                        }
                    }
                }
            }
            if(!isDelete) {
                addDeletesToExample(example,clazz);
            }
        } catch (Exception ex) {
            log.error(ex.getMessage());
            ex.printStackTrace();
        }
        return example;
    }
 
    private static void invokeMethod(Object obj, Method method,String propertyName,List values) throws InvocationTargetException, IllegalAccessException {
        int len = values.size();
        switch (len) {
            case 0:
                if(method.getParameterCount()==1) {
                    method.invoke(obj, propertyName);
                }
                break;
            case 1:
 
                if(method.getParameterCount()==2){
                    method.invoke(obj,propertyName,values.get(0));
                }
                break;
            //between 查询
            case 2:
                if(method.getParameterCount()==3){
                    method.invoke(obj,propertyName,values.toArray());
                }
                break;
            //in 查询
            default:
                if(method.getParameterCount()==2){
                method.invoke(obj,propertyName,values);
                }
                break;
        }
    }
 
    ;
    /**
     * 增加删除条件过滤
     * @param example
     */
    private static void addDeletesToExample(Example example,Class clzz){
        if(isPropertyOfClass(clzz,"isDelete")) {
            List<Example.Criteria> criteriaList = example.getOredCriteria();
            if(criteriaList!=null&&criteriaList.size()>0){
                for(Example.Criteria cri : criteriaList){
                    boolean isHasIsDelete = false;
                    for(Example.Criterion con : cri.getCriteria()){
                          if( con.getCondition().indexOf("is_delete") >-1) {
                              isHasIsDelete = true;
                              break;
                          }
                    }
                    if( !isHasIsDelete) {
                        cri.andNotEqualTo("isDelete", Constants.IS_DELETE_TRUE);
                    }
                }
            }else {
                example.or().andNotEqualTo("isDelete",Constants.IS_DELETE_TRUE);
            }
        }
    }
    private static boolean isPropertyOfClass(Class clzz, String propertyName){
        for(Field field : clzz.getDeclaredFields()) {
            if(field.getName().equals(propertyName)) {
                return  true;
            }
        }
        return false;
    }
 
    private static Method getExampleMethod(String methodName, int paramCount) {
        String criteriaMethodKey = methodName+"_"+String.valueOf(paramCount);
        Method methodTemp = criteriaMethodMap.get(criteriaMethodKey);
        if(methodTemp==null) {
            Method[] methods = Example.Criteria.class.getMethods();
            for (Method method : methods) {
                if(method.getName().equals(methodName)&&method.getParameterCount() == paramCount) {
                    criteriaMethodMap.put(criteriaMethodKey,method);
                    return method;
                }
            }
        }
        return methodTemp;
    }
}