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
|
@Intercepts({ @Signature(type = ResultSetHandler.class, method = "handleResultSets", args = Statement.class) }) public class MyBatisEnumHandlePlugin implements Interceptor {
@Override public Object intercept(Invocation invocation) throws Throwable { DefaultResultSetHandler statementHandler = (DefaultResultSetHandler) invocation.getTarget(); Object proceed = invocation.proceed(); if (proceed instanceof List) { List data = (List) proceed; if (data == null || data.isEmpty()) { return proceed; } List<Map<String, Object>> translationInformation = getTranslationInformation(data.get(0).getClass()); if (translationInformation.isEmpty()) { return proceed; }
for (Object datum : data) { for (Map<String, Object> info : translationInformation) { Field readField = (Field) info.get("read"); Field writeField = (Field) info.get("write"); Map dictValues = (Map) info.get("value"); FieldUtils.writeField(writeField, datum, dictValues.get(readField.get(datum)), true); } } return data; } return proceed; }
@Override public Object plugin(Object o) { return Plugin.wrap(o, this); }
@Override public void setProperties(Properties properties) {
}
private List<Map<String, Object>> getTranslationInformation(Class<?> cls) { ISysDictSV sysDictSV = SpringUtil.getObject(ISysDictSV.class); List<Map<String, Object>> list = new ArrayList<>(); List<DictField> dicts = new ArrayList<>(); getAllDictAnnotation(cls, dicts); if (dicts.isEmpty()) { return list; } for (DictField dictField : dicts) { if (dictField.enumClass().equals(DictEnum.class)) { continue; } Map<String, Object> fieldInfo = new HashMap<>(); String toField = dictField.to(); if ("".equals(toField)) { toField = dictField.from() + "Name"; } Field readField = FieldUtils.getField(cls, dictField.from(), true); Field writeField = FieldUtils.getField(cls, toField, true); Map dictValues = sysDictSV.getDictValues(dictField.enumClass(), dictField.codeType()); if (readField == null || writeField == null || dictValues == null) { continue; } fieldInfo.put("read", readField); fieldInfo.put("write", writeField); fieldInfo.put("value", dictValues); list.add(fieldInfo); } return list; }
private void getAllDictAnnotation(Class<?> cls, List<DictField> fields) { DictEntity annotation = cls.getAnnotation(DictEntity.class); if (annotation != null) { DictField[] value = annotation.value(); fields.addAll(Arrays.asList(value)); } if (cls.getSuperclass() != null && cls.getSuperclass() != BaseSearchModel.class && cls.getSuperclass() != Object.class) { getAllDictAnnotation(cls.getSuperclass(), fields); } } }
|