mybatis-plus分组求和以及Map与Bean的转换

mybatis-plus、Map转对象

Posted by John Doe on 2021-02-16
Words 308 and Reading Time 1 Minutes
Viewed Times

mybatis-plus分组求和

平常lambdaQuery写习惯了突然发现lambdaQuery好像不能求和,捡一下QueryWrapper写法

1
2
3
4
QueryWrapper<Entity> yearQueryWrapper = new QueryWrapper<>();
yearQueryWrapper.select("bid_year as name,sum(amount) as value");
yearQueryWrapper.groupBy("bid_year").orderByAsc("bid_year");
List<Map<String, Object>> yearMapList= bidInforService.listMaps(yearQueryWrapper);

groupby多个字段

1
2
3
4
5
6
7
// 源码信息
default Children groupBy(R... columns) {
return this.groupBy(true, columns);
}


QueryWrapper.groupBy("bid_year","bid_month");

map与javaBean对象转换

方法一:用Apache BeanUtils将Map转Bean

1
2
3
4
5
6
7
// 用apache的BeanUtils实现Map covert to Bean
Map<String,String> map=new HashMap<>();
User user=new User();
map.put("userName","wang shisheng");
map.put("passWord","xxxxx44333");

BeanUtils.populate(user,map);

方法二:自封装工具类

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
public class MapToObjectUtil {
public static <T> T map2Object(Map<String, Object> map, Class<T> clazz) {
if (map == null) {
return null;
}
T obj = null;
try {
obj = clazz.newInstance();

Field[] fields = obj.getClass().getDeclaredFields();
for (Field field : fields) {
int mod = field.getModifiers();
if (Modifier.isStatic(mod) || Modifier.isFinal(mod)) {
continue;
}
field.setAccessible(true);
String filedTypeName = field.getType().getName();
if (filedTypeName.equalsIgnoreCase("java.util.date")) {
String datetimestamp = String.valueOf(map.get(field.getName()));
if (datetimestamp.equalsIgnoreCase("null")) {
field.set(obj, null);
} else {
field.set(obj, new Date(Long.parseLong(datetimestamp)));
}
} else {
field.set(obj, map.get(field.getName()));
}
}
} catch (Exception e) {
e.printStackTrace();
}
return obj;
}
}

实战使用:

1
List<Entity> yearList = yearMapList.stream().map(item -> MapToObjectUtil.map2Object(item, Entity.class)).collect(Collectors.toList());


This is copyright.

...

...

00:00
00:00