shikeying
2024-01-11 3b67e947e36133e2a40eb2737b15ea375e157ea0
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
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
package com.walker.jdbc;
 
import com.fasterxml.jackson.databind.node.ArrayNode;
import com.walker.infrastructure.utils.JsonUtils;
import com.walker.jdbc.dao.PersistenceException;
import com.walker.jdbc.util.StringUtils;
 
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.IdentityHashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
 
/**
 * <pre>
 * 该类有两个用处,一是绑定页面查询条件,二是生成and形式的查询条件。
 * Contorller中:
 *   &#64;ModelAttribute("queryVo") QueryVo queryVo
 * Service中:
 *   sql = sql.append(queryVo.generateAndSql()); 生成and形式的sql语句
 *   queryVo.getQueryMap() 生成对应的sql语句参数
 *   如需非页面中的查询条件,可使用putLike,putEqual方法自行添加查询条件
 * 页面中:
 *  input type="text" name="likeItem['rz.username']" value="${queryVo.likeItem['rz.username']}"
 *   其中likeItem表示模糊查询,equalItem表示精确查询。
 *   如果要使用别名可用 别名.字段名
 * 注:暂不支持字段名别名的情况
 * </pre>
 *
 * @author 张亮
 * @author 时克英 修改
 * @date 2022-10-10
 */
public class QueryVo implements Serializable {
    // 序列化版本号
    private static final long serialVersionUID = 1L;
 
    public static final String SPACE = " ";
 
    /**
     * 常用sql语句组成片段
     */
    private static final String PERCENT = "%";
    private static final String LIKE = " like ";
    private static final String AND = " and ";
    private static final String OR = " or ";
 
    private static final String EQUAL = " = ";
    private static final String UNEQUAL = " != ";
    private static final String IN = " in ";
    private static final String NOTIN = " not in ";
    private static final String GREATER = " >= ";
    private static final String LESS = " <= ";
    private static final String WHERE = " where ";
    private static final String ORDER_BY = " order by ";
    /**
     * 等于、相似、大于、小于、不等于、包含、不包含对象
     */
    private Map<String, Object> equalItem;
    private Map<String, Object> likeItem;
    private Map<String, Object> greaterItem;
    private Map<String, Object> lessItem;
    private Map<String, Object> unequalItem;
    private Map<String, Object> includeItem;
    private Map<String, Object> notincludeItem;
 
    //默认添加后缀
    private Map<String, Object> defalutSuffixItem;
    private Integer sfzsgd;
 
    /**
     * 记录非重复变量
     */
    private Map<String, Object> countMap;
    private List keyList;
    /**
     * 自定义sql
     */
    private StringBuilder extSql;
    /**
     * 自定义order by sql
     */
    private StringBuilder orderBySql;
    /**
     * 排序用字段名,正序倒序
     */
    private String qvSortName;
    private String qvSortOrder;
    /**
     * 列选择的所有数据
     */
    private String toggleColumnValue = "";
    /**
     * 生成的查询语句用值
     */
    private Map<String, Object> queryMap;
    /**
     * 保存页面查询条件字符串
     */
    private String serializeQuery = "";
    /**
     * 临时排除查询条件
     */
    private Map<String, Object> excludeQueryVO;
 
    private  List<Map<String,Object>> labelCount;
 
 
    public QueryVo() {
        equalItem = new SaveIdentityHashMap<>();
        likeItem = new SaveIdentityHashMap<>();
        greaterItem = new SaveIdentityHashMap<>();
        lessItem = new SaveIdentityHashMap<>();
        countMap = new SaveIdentityHashMap<>();
        unequalItem = new SaveIdentityHashMap<>();
        includeItem = new SaveIdentityHashMap<>();
        notincludeItem = new SaveIdentityHashMap<>();
        defalutSuffixItem = new HashMap<>();
        excludeQueryVO = new HashMap<>();
        keyList = new ArrayList<>();
        labelCount = new ArrayList<>();
        queryMap = new HashMap<>();
        extSql = new StringBuilder();
        orderBySql = new StringBuilder();
        qvSortName = null;
        qvSortOrder = null;
    }
 
    /**
     * 生成and格式的sql,默认不带where
     *
     * @return
     * @author 张亮
     */
    public StringBuffer generateAndSql() {
        return generateAndSql(false);
    }
 
    /**
     * 生成and格式的sql,可选择是否带where
     *
     * @return
     * @author 张亮
     */
    public StringBuffer generateAndSql(boolean generateWhere) {
        StringBuffer whereQuery = new StringBuffer(SPACE);
        boolean paramEmpty = true;
        paramEmpty = genSql(equalItem, whereQuery, paramEmpty, EQUAL, false, generateWhere, keyList, countMap);
        paramEmpty = genSql(likeItem, whereQuery, paramEmpty, LIKE, true, generateWhere, keyList, countMap);
        paramEmpty = genSql(greaterItem, whereQuery, paramEmpty, GREATER, false, generateWhere, keyList, countMap);
        paramEmpty = genSql(lessItem, whereQuery, paramEmpty, LESS, false, generateWhere, keyList, countMap);
        paramEmpty = genSql(unequalItem, whereQuery, paramEmpty, UNEQUAL, false, generateWhere, keyList, countMap);
        paramEmpty = genSql(includeItem, whereQuery, paramEmpty, IN, false, generateWhere, keyList, countMap);
        paramEmpty = genSql(notincludeItem, whereQuery, paramEmpty, NOTIN, false, generateWhere, keyList, countMap);
        //附加sql不为空才生成
        if (!extSql.toString().equals(com.walker.infrastructure.utils.StringUtils.EMPTY_STRING)) {
            if (generateWhere && paramEmpty) {
                //需要生成where没有参数
                whereQuery.append(WHERE).append(extSql);
            } else {
                //不需要生成where没有参数
                whereQuery.append(AND).append(extSql);
            }
        }
        if(excludeQueryVO.size()==0) {//如果有排除分组函数,不执行排序
            if (StringUtils.isNotEmpty(qvSortName)) {
                if (StringUtils.isNotEmpty(qvSortOrder)) {
                    whereQuery.append(ORDER_BY + qvSortName + SPACE + qvSortOrder);
                }
            } else {
                if (StringUtils.isNotEmpty(orderBySql.toString())) {
                    whereQuery.append(SPACE).append(orderBySql);
                }
            }
        }
 
        return whereQuery.append(SPACE);
    }
 
    private boolean genSql(Map<String, Object> item, StringBuffer whereQuery, boolean paramEmpty, String operator, boolean like, boolean generateWhere, List keyList, Map<String, Object> countMap) {
 
        boolean flag_in=operator.equals(IN) || operator.equals(NOTIN);
        for (Map.Entry<String, Object> entry : item.entrySet()) {
            if(excludeQueryVO.containsKey(entry.getKey())){
                continue;
            }
            String key = "";
            if (keyList.contains(entry.getKey())) {
                if (!countMap.containsKey(entry.getKey())) {
                    countMap.put(entry.getKey(), 0);
                } else {
                    countMap.put(entry.getKey(), countMap.get(entry.getKey() + 1));
                }
                key = entry.getKey() + com.walker.infrastructure.utils.StringUtils.STRING_UNDERLINE + countMap.get(entry.getKey());
            } else {
                keyList.add(entry.getKey());
                key = entry.getKey();
            }
 
            if (StringUtils.isNotEmpty(String.valueOf(entry.getValue())) && !String.valueOf(entry.getValue()).equalsIgnoreCase("[]")) {
                if(flag_in){
                    if (generateWhere && paramEmpty) {
                        whereQuery.append(WHERE + entry.getKey() + operator + "(:" + key+")");
                        generateWhere = false;
                    } else {
                        whereQuery.append(AND + entry.getKey() + operator +  "(:" + key+")");
                    }
                    List<Object> value=new ArrayList<>();
                    if(entry.getValue().toString().startsWith("[") && entry.getValue().toString().endsWith("]")){
//                        JSONArray array= new JSONArray(entry.getValue().toString());
//                        if(array.length()>0&&array.get(0).toString().startsWith(";")&&array.get(0).toString().endsWith(";")) {
//                            for (int i = 0; i < array.length(); i++) {
//                                String v = array.get(i).toString();
//                                value.add(v.substring(1, v.length() - 1));
//                            }
//                        }else{
//                            value=array.toList();
//                        }
                        try {
                            ArrayNode arrayNode = JsonUtils.toJsonArray(entry.getValue().toString());
                            if(arrayNode.size() > 0
                                    && arrayNode.get(0).toString().startsWith(";") && arrayNode.get(0).toString().endsWith(";")){
                                for (int i = 0; i < arrayNode.size(); i++) {
                                    String v = arrayNode.get(i).toString();
                                    value.add(v.substring(1, v.length() - 1));
                                }
                            } else {
                                for (int i = 0; i < arrayNode.size(); i++) {
                                    value.add(arrayNode.get(i).toString());
                                }
                            }
                        } catch (Exception e) {
                            throw new RuntimeException(e);
                        }
 
                    }else{
                        if(entry.getValue().toString().startsWith(";")&&entry.getValue().toString().endsWith(";")) {
                            List<String> templist=Arrays.asList(String.valueOf(entry.getValue()).trim().split(","));
                            for (String tv:templist) {
                                value.add(tv.substring(1, tv.length() - 1));
                            }
                        }else{
                            value=Arrays.asList(String.valueOf(entry.getValue()).trim().split(com.walker.infrastructure.utils.StringUtils.DEFAULT_SPLIT_SEPARATOR));
                        }
                        value.remove("");
                    }
                    queryMap.put(key, value);
                }else {
                    if (generateWhere && paramEmpty) {
                        whereQuery.append(WHERE + entry.getKey() + operator + ":" + key);
                    } else {
                        whereQuery.append(AND + entry.getKey() + operator + ":" + key);
                    }
                    String value = "";
                    if (like) {
                        value = PERCENT + String.valueOf(entry.getValue()).trim() + PERCENT;
                    } else {
                        if(defalutSuffixItem.containsKey(key)){
                            value = String.valueOf(entry.getValue()).trim()+defalutSuffixItem.get(key);
                        }else{
                            value = String.valueOf(entry.getValue()).trim();
                        }
                    }
                    paramEmpty = false;
                    queryMap.put(key, value);
                }
            }
        }
        return paramEmpty;
    }
 
    /**
     * 获取sql查询用的参数Map("key","value")
     *
     * @return
     * @author 张亮
     */
    public Map<String, Object> getQueryMap() {
        return queryMap;
    }
 
    /**
     * 增加order by语句
     *
     * @param orderBySqlOnce 自己定义的order by语句
     */
    public void appendOrderBySql(String orderBySqlOnce) {
        orderBySql.append(orderBySqlOnce);
    }
 
    /**
     * 增加一段自己定义的sql语句
     *
     * @param extSqlonce 自己定义的sql语句
     * @return
     */
    public void appendExtSql(String extSqlonce) {
        extSql.append(extSqlonce);
    }
 
    /**
     * 增加一个等于查询条件
     *
     * @param key
     * @param value
     */
    public void addEqualItem(String key, Object value) {
        equalItem.put(key, value);
    }
 
    /**
     * 增加一个like查询条件
     *
     * @param key
     * @param value
     */
    public void addLikeItem(String key, Object value) {
        likeItem.put(key, value);
    }
    public void addIncludeItem(String key, Object value) {
        includeItem.put(key, value);
    }
    public void initIncludeItem(String key,Object value){ includeItem.put(key,";"+value+";");}
 
    /**
     * 增加一个小于查询条件
     *
     * @param key
     * @param value
     */
    public void addLessItem(String key, Object value) {
        lessItem.put(key, value);
    }
 
    /**
     * 增加一个大于查询条件
     *
     * @param key
     * @param value
     */
    public void addGreaterItem(String key, Object value) {
        greaterItem.put(key, value);
    }
 
    /**
     * 增加一个不等于的变量
     *
     * @param key
     * @param value
     */
    public void addUnequalItem(String key, Object value) {
        unequalItem.put(key, value);
    }
 
    /**
     * 增加一个绑定变量值
     *
     * @param key
     * @param value
     */
    public void addQueryMap(String key, Object value) {
        queryMap.put(key, value);
    }
 
    /**
     * 增加一组绑定变量值
     *
     * @param map
     */
    public void addQueryMap(Map map) {
        queryMap.putAll(map);
    }
 
    /**
     * 获取一个equal变量
     *
     * @param key
     * @return equalItem中的一个变量
     */
    public Object getEqualItemValue(String key) {
        return getObject(equalItem, key);
    }
    /**
     * 获取一个include变量
     *
     * @param key
     * @return includeItem中的一个变量
     */
    public Object getIncludeItemValue(String key) {
        return getObject(includeItem, key);
    }
 
    /**
     * 获取一个like变量
     *
     * @param key
     * @return
     */
    public Object getLikeItemValue(String key) {
        return getObject(likeItem, key);
    }
 
    private Object getObject(Map<String, Object> item, String key) {
        for (Map.Entry<String, Object> entry : item.entrySet()) {
            if (entry.getKey().equals(key)) {
                return entry.getValue();
            }
        }
        return null;
    }
 
    public Map<String, Object> getEqualItem() {
        return equalItem;
    }
 
    public void setEqualItem(Map<String, Object> equalItem) {
        this.equalItem = equalItem;
    }
 
    public Map<String, Object> getLikeItem() {
        return likeItem;
    }
 
    public void setLikeItem(Map<String, Object> likeItem) {
        this.likeItem = likeItem;
    }
 
    public String getToggleColumnValue() {
        return toggleColumnValue;
    }
 
    public void setToggleColumnValue(String toggleColumnValue) {
        this.toggleColumnValue = toggleColumnValue;
    }
 
    public String getSerializeQuery() {
        return serializeQuery;
    }
 
    public void setSerializeQuery(String serializeQuery) {
        this.serializeQuery = serializeQuery;
    }
 
    public Map<String, Object> getLessItem() {
        return lessItem;
    }
 
    public void setLessItem(Map<String, Object> lessItem) {
        this.lessItem = lessItem;
    }
 
    public Map<String, Object> getGreaterItem() {
        return greaterItem;
    }
 
    public void setGreaterItem(Map<String, Object> greaterItem) {
        this.greaterItem = greaterItem;
    }
 
    public Map<String, Object> getUnequalItem() {
        return unequalItem;
    }
 
    public void setUnequalItem(Map<String, Object> unequalItem) {
        this.unequalItem = unequalItem;
    }
 
    public Map<String, Object> getIncludeItem() {
        return includeItem;
    }
 
    public void setIncludeItem(Map<String, Object> includeItem) {
        this.includeItem = includeItem;
    }
 
    public Map<String, Object> getNotincludeItem() {
        return notincludeItem;
    }
 
    public void setNotincludeItem(Map<String, Object> notincludeItem) {
        this.notincludeItem = notincludeItem;
    }
 
    public Map<String, Object> getDefalutSuffixItem() {
        return defalutSuffixItem;
    }
 
    public void setDefalutSuffixItem(Map<String, Object> defalutSuffixItem) {
        this.defalutSuffixItem = defalutSuffixItem;
    }
 
    /**
     * 增加一个绑定变量值
     *
     * @param key
     * @param value
     */
    public void addExcludeQueryVO(String key, Object value) {
        excludeQueryVO.put(key, value);
    }
    public Map<String, Object> getExcludeQueryVO() {
        return excludeQueryVO;
    }
    public void clearExcludeQueryVO(){
        excludeQueryVO.clear();
        keyList.clear();
        countMap.clear();
    }
 
    public List<Map<String, Object>> getLabelCount() {
        return labelCount;
    }
 
    public void setLabelCount(List<Map<String, Object>> labelCount) {
        this.labelCount = labelCount;
    }
 
    public static long getSerialVersionUID() {
        return serialVersionUID;
    }
 
    public String getQvSortName() {
        return qvSortName;
    }
 
    public void setQvSortName(String qvSortName) {
        if(!columnCheck(qvSortName)) {
            throw new PersistenceException(qvSortName+"为非法的属性值");
        }
        this.qvSortName = qvSortName;
    }
 
    public String getQvSortOrder() {
        return qvSortOrder;
    }
 
    public void setQvSortOrder(String qvSortOrder) {
        if(StringUtils.isNotEmpty(qvSortOrder)) {
            if(!qvSortOrder.equalsIgnoreCase("DESC")&&!qvSortOrder.equalsIgnoreCase("ASC")) {
                throw new PersistenceException(qvSortName+"为非法的关键字");
            }
        }
        this.qvSortOrder = qvSortOrder;
    }
 
    public Integer getSfzsgd() {
        if(sfzsgd==null){
            sfzsgd = 0;
        }
        return sfzsgd;
    }
 
    public void setSfzsgd(Integer sfzsgd) {
        this.sfzsgd = sfzsgd;
    }
 
    private static Pattern p = Pattern.compile("^[A-Za-z0-9_\\.]+$");
 
    /**
     * 检查列名是否合法
     * @param column
     * @return
     */
    private boolean columnCheck(String column) {
        if(column == null ||column.isEmpty()) {
            return true;
        } else {
            Matcher m = p.matcher(column);
            return m.matches();
        }
    }
 
    class SaveIdentityHashMap<K, V> extends IdentityHashMap<K, V> {
        @Override
        public V put(K k, V v) {
            if(!columnCheck(k.toString())) {
                throw new PersistenceException(k+"为非法的属性名");
            }
            return super.put(k, v);
        }
    }
}