BAOLH
2025-09-19 d4658f198bed2f67ce8af33daa361a8a43df7586
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
/*
 *  Copyright 2019-2020 Zheng Jie
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *  http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */
package me.zhengjie.utils;
 
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ObjectUtil;
import lombok.extern.slf4j.Slf4j;
import me.zhengjie.annotation.DataPermission;
import me.zhengjie.annotation.Query;
import javax.persistence.criteria.*;
import java.lang.reflect.Field;
import java.util.*;
 
/**
 * @author Zheng Jie
 * @date 2019-6-4 14:59:48
 */
@Slf4j
@SuppressWarnings({"unchecked","all"})
public class QueryHelp {
 
    public static <R, Q> Predicate getPredicate(Root<R> root, Q query, CriteriaBuilder cb) {
        List<Predicate> list = new ArrayList<>();
        if(query == null){
            return cb.and(list.toArray(new Predicate[0]));
        }
        // 数据权限验证
        DataPermission permission = query.getClass().getAnnotation(DataPermission.class);
        if(permission != null){
            // 获取数据权限
            List<Long> dataScopes = SecurityUtils.getCurrentUserDataScope();
            if(CollectionUtil.isNotEmpty(dataScopes)){
                if(StringUtils.isNotBlank(permission.joinName()) && StringUtils.isNotBlank(permission.fieldName())) {
                    Join join = root.join(permission.joinName(), JoinType.LEFT);
                    list.add(getExpression(permission.fieldName(),join, root).in(dataScopes));
                } else if (StringUtils.isBlank(permission.joinName()) && StringUtils.isNotBlank(permission.fieldName())) {
                    list.add(getExpression(permission.fieldName(),null, root).in(dataScopes));
                }
            }
        }
        try {
            List<Field> fields = getAllFields(query.getClass(), new ArrayList<>());
 
            Map<String, List<Predicate>> orGroupMap = new HashMap<String, List<Predicate>>();
 
            for (Field field : fields) {
                boolean accessible = field.isAccessible();
                // 设置对象的访问权限,保证对private的属性的访
                field.setAccessible(true);
                Query q = field.getAnnotation(Query.class);
                if (q != null) {
                    String propName = q.propName();
                    String joinName = q.joinName();
                    String blurry = q.blurry();
                    // wcd加
                    String isOr = q.isOr();
                    //
                    String attributeName = isBlank(propName) ? field.getName() : propName;
                    Class<?> fieldType = field.getType();
                    Object val = field.get(query);
                    if (ObjectUtil.isNull(val) || "".equals(val)) {
                        continue;
                    }
                    Join join = null;
                    // 模糊多字段
                    if (ObjectUtil.isNotEmpty(blurry)) {
                        String[] blurrys = blurry.split(",");
                        List<Predicate> orPredicate = new ArrayList<>();
                        for (String s : blurrys) {
                            String[] joinNames = s.split(">");
                            if (joinNames.length == 2) {
                                orPredicate.add(cb.like(root.join(joinNames[0], JoinType.LEFT).get(joinNames[1])
                                        .as(String.class), "%" + val.toString() + "%"));
                            } else {
                                orPredicate.add(cb.like(root.get(joinNames[0])
                                        .as(String.class), "%" + val.toString() + "%"));
                            }
                        }
                        Predicate[] p = new Predicate[orPredicate.size()];
                        list.add(cb.or(orPredicate.toArray(p)));
                        continue;
                    }
                    if (ObjectUtil.isNotEmpty(joinName)) {
                        String[] joinNames = joinName.split(">");
                        for (String name : joinNames) {
                            switch (q.join()) {
                                case LEFT:
                                    if(ObjectUtil.isNotNull(join) && ObjectUtil.isNotNull(val)){
                                        join = join.join(name, JoinType.LEFT);
                                    } else {
                                        join = root.join(name, JoinType.LEFT);
                                    }
                                    break;
                                case RIGHT:
                                    if(ObjectUtil.isNotNull(join) && ObjectUtil.isNotNull(val)){
                                        join = join.join(name, JoinType.RIGHT);
                                    } else {
                                        join = root.join(name, JoinType.RIGHT);
                                    }
                                    break;
                                case INNER:
                                    if(ObjectUtil.isNotNull(join) && ObjectUtil.isNotNull(val)){
                                        join = join.join(name, JoinType.INNER);
                                    } else {
                                        join = root.join(name, JoinType.INNER);
                                    }
                                    break;
                                default: break;
                            }
                        }
                    }
 
                    // wcd加
                    if (ObjectUtil.isNotEmpty(isOr)) {
                        String[] isOrs = isOr.split(",");
                        List<Predicate> orP = new ArrayList<>();
                        for (String s : isOrs) {
                            orP.add(cb.equal(root.get(s)
                                    .as(String.class),  val));
                        }
                        Predicate[] orpr = new Predicate[orP.size()];
                        list.add(cb.or(orP.toArray(orpr)));
                        continue;
                    }
                    //
 
                    String orGroup = q.orGroup();
                    if (ObjectUtil.isNotEmpty(orGroup)) {
                        if (orGroupMap.get(orGroup) == null) {
                            orGroupMap.put(orGroup, new ArrayList<Predicate>());
                        }
                        List<Predicate> predicates = orGroupMap.get(orGroup);
                        switch (q.type()) {
                            case EQUAL:
                                predicates.add(cb.equal(getExpression(attributeName,join,root)
                                        .as((Class<? extends Comparable>) fieldType),val));
                                break;
                            case GREATER_THAN:
                                predicates.add(cb.greaterThanOrEqualTo(getExpression(attributeName,join,root)
                                        .as((Class<? extends Comparable>) fieldType), (Comparable) val));
                                break;
                            case LESS_THAN:
                                predicates.add(cb.lessThanOrEqualTo(getExpression(attributeName,join,root)
                                        .as((Class<? extends Comparable>) fieldType), (Comparable) val));
                                break;
                            case LESS_THAN_NQ:
                                predicates.add(cb.lessThan(getExpression(attributeName,join,root)
                                        .as((Class<? extends Comparable>) fieldType), (Comparable) val));
                                break;
                            case INNER_LIKE:
                                predicates.add(cb.like(getExpression(attributeName,join,root)
                                        .as(String.class), "%" + val.toString() + "%"));
                                break;
                            case LEFT_LIKE:
                                predicates.add(cb.like(getExpression(attributeName,join,root)
                                        .as(String.class), "%" + val.toString()));
                                break;
                            case RIGHT_LIKE:
                                predicates.add(cb.like(getExpression(attributeName,join,root)
                                        .as(String.class), val.toString() + "%"));
                                break;
                            case IN:
                                if (CollUtil.isNotEmpty((Collection<Object>)val)) {
                                    predicates.add(getExpression(attributeName,join,root).in((Collection<Object>) val));
                                }
                                break;
                            case NOT_IN:
                                if (CollUtil.isNotEmpty((Collection<Object>)val)) {
                                    predicates.add(getExpression(attributeName,join,root).in((Collection<Object>) val).not());
                                }
                                break;
                            case NOT_EQUAL:
                                predicates.add(cb.notEqual(getExpression(attributeName,join,root), val));
                                break;
                            case NOT_NULL:
                                predicates.add(cb.isNotNull(getExpression(attributeName,join,root)));
                                break;
                            case IS_NULL:
                                predicates.add(cb.isNull(getExpression(attributeName,join,root)));
                                break;
                            case BETWEEN:
                                List<Object> between = new ArrayList<>((List<Object>)val);
                                predicates.add(cb.between(getExpression(attributeName, join, root).as((Class<? extends Comparable>) between.get(0).getClass()),
                                        (Comparable) between.get(0), (Comparable) between.get(1)));
                                break;
                            default: break;
                        }
                    } else {
                        switch (q.type()) {
                            case EQUAL:
                                list.add(cb.equal(getExpression(attributeName,join,root)
                                        .as((Class<? extends Comparable>) fieldType),val));
                                break;
                            case GREATER_THAN:
                                list.add(cb.greaterThanOrEqualTo(getExpression(attributeName,join,root)
                                        .as((Class<? extends Comparable>) fieldType), (Comparable) val));
                                break;
                            case LESS_THAN:
                                list.add(cb.lessThanOrEqualTo(getExpression(attributeName,join,root)
                                        .as((Class<? extends Comparable>) fieldType), (Comparable) val));
                                break;
                            case LESS_THAN_NQ:
                                list.add(cb.lessThan(getExpression(attributeName,join,root)
                                        .as((Class<? extends Comparable>) fieldType), (Comparable) val));
                                break;
                            case INNER_LIKE:
                                list.add(cb.like(getExpression(attributeName,join,root)
                                        .as(String.class), "%" + val.toString() + "%"));
                                break;
                            case LEFT_LIKE:
                                list.add(cb.like(getExpression(attributeName,join,root)
                                        .as(String.class), "%" + val.toString()));
                                break;
                            case RIGHT_LIKE:
                                list.add(cb.like(getExpression(attributeName,join,root)
                                        .as(String.class), val.toString() + "%"));
                                break;
                            case IN:
                                if (CollUtil.isNotEmpty((Collection<Object>)val)) {
                                    list.add(getExpression(attributeName,join,root).in((Collection<Object>) val));
                                }
                                break;
                            case NOT_IN:
                                if (CollUtil.isNotEmpty((Collection<Object>)val)) {
                                    list.add(getExpression(attributeName,join,root).in((Collection<Object>) val).not());
                                }
                                break;
                            case NOT_EQUAL:
                                list.add(cb.notEqual(getExpression(attributeName,join,root), val));
                                break;
                            case NOT_NULL:
                                list.add(cb.isNotNull(getExpression(attributeName,join,root)));
                                break;
                            case IS_NULL:
                                list.add(cb.isNull(getExpression(attributeName,join,root)));
                                break;
                            case BETWEEN:
                                List<Object> between = new ArrayList<>((List<Object>)val);
                                list.add(cb.between(getExpression(attributeName, join, root).as((Class<? extends Comparable>) between.get(0).getClass()),
                                        (Comparable) between.get(0), (Comparable) between.get(1)));
                                break;
                            default: break;
                        }
                    }
                }
                field.setAccessible(accessible);
            }
            orGroupMap.values().forEach(predicates -> list.add(cb.or(predicates.toArray(new Predicate[0]))));
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        }
        int size = list.size();
        return cb.and(list.toArray(new Predicate[size]));
    }
 
    @SuppressWarnings("unchecked")
    private static <T, R> Expression<T> getExpression(String attributeName, Join join, Root<R> root) {
        if (ObjectUtil.isNotEmpty(join)) {
            return join.get(attributeName);
        } else {
            return root.get(attributeName);
        }
    }
 
    private static boolean isBlank(final CharSequence cs) {
        int strLen;
        if (cs == null || (strLen = cs.length()) == 0) {
            return true;
        }
        for (int i = 0; i < strLen; i++) {
            if (!Character.isWhitespace(cs.charAt(i))) {
                return false;
            }
        }
        return true;
    }
 
    public static List<Field> getAllFields(Class clazz, List<Field> fields) {
        if (clazz != null) {
            fields.addAll(Arrays.asList(clazz.getDeclaredFields()));
            getAllFields(clazz.getSuperclass(), fields);
        }
        return fields;
    }
}