通过反射简单设置字典,不用每个需要用字典的地方都重新写一遍
/**
* @param dictType 字典type
* @param dictField 字典type对应字段名
* @param dictFieldName 需要填充中文的字段名
* @param <T>
*/
<T> void setDictName(T obj, String dictType, String dictField,String dictFieldName);
/**
* @param dictType 字典type
* @param dictField 字典type对应字段名
* @param dictFieldName 需要填充中文的字段名
* @param <T>
*/
@Override
public <T> void setDictName(T obj, String dictType, String dictField,String dictFieldName) {
try{
if (obj != null){
LambdaQueryWrapper<SysDictData> queryWrapper = new LambdaQueryWrapper<>();
queryWrapper.eq(SysDictData::getDictType,dictType);
queryWrapper.eq(SysDictData::getStatus,"0");
Field field = obj.getClass().getDeclaredField(dictField);
Field fieldName = obj.getClass().getDeclaredField(dictFieldName);
fieldName.setAccessible(true);
field.setAccessible(true);
String fieldValue = field.get(obj).toString();
queryWrapper.eq(SysDictData::getDictValue,fieldValue);
List<SysDictData> sysDictData = this.selectDictDataByType(dictType);
SysDictData one = sysDictData.stream()
.filter(data -> "0".equals(data.getStatus()) && fieldValue.equals(data.getDictValue()))
.findFirst()
.orElse(null);
if (one != null){
fieldName.set(obj,one.getDictLabel());
}
}
}catch (Exception e){
log.error("字典映射错误,请联系管理员");
throw new RuntimeException("字典映射错误,请联系管理员");
}
}
代码结合到业务表的 大概意思差不多
下面是list版本的
/**
*
* @param list 数据list
* @param dictType 字典type
* @param dictField 字典type对应字段名
* @param dictFieldName 需要填充中文的字段名
* @param <T>
*/
@Override
public <T> void setDictNameByList(List<T> list, String dictType, String dictField,String dictFieldName) {
try{
if (!CollectionUtils.isEmpty(list)){
List<SysDictData> sysDictData = this.selectDictDataByType(dictType);
List<SysDictData> dicts = sysDictData.stream().filter(data->"0".equals(data.getStatus())).collect(Collectors.toList());
Map<String, SysDictData> collect = dicts.stream().collect(Collectors.toMap(SysDictData::getDictValue, e -> e));
for (T t : list) {
Field field = t.getClass().getDeclaredField(dictField);
Field fieldName = t.getClass().getDeclaredField(dictFieldName);
fieldName.setAccessible(true);
field.setAccessible(true);
if (collect.containsKey(field.get(t).toString())){
fieldName.set(t,collect.get(field.get(t).toString()).getDictLabel());
}
}
}
} catch (Exception e){
log.error("字典映射错误,请联系管理员");
throw new RuntimeException(e.getMessage());
}
}
标签:dictType,dictFieldName,String,映射,dictField,param,简单,字典 From: https://www.cnblogs.com/bawanglong168/p/18303311