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
package com.yanzuoguang.dao.impl;
import com.yanzuoguang.dao.cond.SqlCond;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* 将条件排序,符合索引
*
* @author 颜佐光
*/
class SqlCondUtil {
/**
* 代码片段等级
*/
public static final int FIELD_CODE = 0;
/**
* 时间等级
*/
public static final int WHERE_DATE = 1;
/**
* ID等级
*/
public static final int WHERE_ID = 2;
/**
* 普通相等
*/
public static final int WHERE_COMMON = 3;
/**
* 普通IN,NOT IN
*/
public static final int WHERE_IN = 4;
/**
* Like条件
*/
public static final int WHERE_LIKE = 5;
/**
* 全文索引
*/
public static final int WHERE_MATCH = 6;
/**
* 将SQL语句条件排序,符合索引
*
* @param fields
*/
public static List<SqlDataField> sortCond(List<SqlDataField> fields) {
// 获取代码片段的级别,并且放到对应级别的数组中
Map<Integer, List<SqlDataField>> mapLevel = new HashMap<>();
for (SqlDataField field : fields) {
int level = getCondLevel(field);
List<SqlDataField> levelCond = mapLevel.get(level);
if (levelCond == null) {
levelCond = new ArrayList<>();
mapLevel.put(level, levelCond);
}
levelCond.add(field);
}
// 按照级别返回代码片段
List<SqlDataField> tos = new ArrayList<>();
for (int i = 0; i <= WHERE_MATCH; i++) {
List<SqlDataField> levelCond = mapLevel.get(i);
if (levelCond == null) {
continue;
}
tos.addAll(levelCond);
}
return tos;
}
private static int getCondLevel(SqlDataField field) {
if (field == null) {
return WHERE_COMMON;
}
SqlCond<?> cond = field.getCond();
int len = field.getCodes().size() / 2;
for (int i = 0; i < len; i++) {
// 判断是否包含where条件,当没有包含where条件时,则属于普通代码片段,优先级最高
String codeName = field.getCodes().get(i * 2).toLowerCase();
String codeValue = field.getCodes().get(i * 2 + 1).toLowerCase();
if (codeName.indexOf("where") < 0) {
continue;
}
// 当包含where条件时,则按照规则排序
for (String fieldName : cond.getFields()) {
fieldName = fieldName.toLowerCase();
if (fieldName.indexOf("date") > -1 || fieldName.indexOf("time") > -1) {
return WHERE_DATE;
} else if (fieldName.indexOf("id") > -1) {
return WHERE_ID;
}
}
if (codeValue.indexOf("in") > -1) {
return WHERE_IN;
} else if (codeValue.indexOf("like") > -1) {
return WHERE_LIKE;
} else if (codeValue.indexOf("match") > -1) {
return WHERE_MATCH;
} else {
return WHERE_COMMON;
}
}
return FIELD_CODE;
}
}