mybatis group by 分组查询:将返回结果封装为map

x33g5p2x  于2022-05-05 转载在 其他  
字(1.9k)|赞(0)|评价(0)|浏览(308)

1. 最简单但性能最差的做法

在逻辑层分多次对数据库进行查询。伪代码如下。

List<String> nameList ;
List<Integer> countList;
for(String name: nameList){
countList.add(xxDao.countByName(name));
}

map文件如下。

<select>
	select cout(*) from ** where name=#{name};
</select>

这样写起来很简单,但是反复建立与数据库的连接,效率极差。

2. 使用group by分组查询,将查询结果封装成类

为了提高性能,使用数据库中 group by 的语法,直接进行分组查询,并定义一个类接受查询结果。

//结果类
public class result{
private String key;
private String value;
//省略getter和setter
}

map文件如下。

<resultMap type="com.**.result" id="result">…</resultMap>
<select resuleMap="result">
select name as key , count(*) as value group by name;
</select>

然后再对List进行处理,这样效率比第一种方法高,但是建立result对象会有一定内存消耗,对类进行处理也并不方便。

3.group by分组查询,将结果封装为map。

直接封装为map?

<select id="getDepNumMap" resultType="java.util.HashMap">
        select department_id , count(*) 
        from staff_career_info
        where status = 'enable'
        group by department_id;
    </select>

想用上面这样的代码直接将查询结果封装到map中是不可以的。返回结果如下:

可见,这样得到的map中将column的名字作为了key,结果作为value。而且,如果有多个分组也只会返回一个分组。

List<HashMap<String,Object>>

正确的做法如下。

//Dao
List<HashMap<String,Object>> getDepNumMap();
//map文件
    <select id="getDepNumMap" resultType="java.util.HashMap">
        select department_id as 'key', count(*) as 'value'
        from staff_career_info
        where status = 'enable'
        group by department_id;
    </select>

然后再将得到的list 转化为map。这里的方法要自己写。

//转换方法
List<HashMap<String, Object>> list = sysStaffCareerInfoDao.getDepNumMap();
Map<String, Integer> map = new HashMap<>();
if (list != null && !list.isEmpty()) {
	for (HashMap<String, Object> hashMap : list) {
    	String key = null;
        Integer value = null;
        for (Map.Entry<String, Object> entry : hashMap.entrySet()) {
 	       if ("key".equals(entry.getKey())) {
 	       		key = (String) entry.getValue();
           } else if ("value".equals(entry.getKey())) {
           		//我需要的是int型所以做了如下转换,实际上返回的object应为Long。
                value = ((Long)entry.getValue()).intValue();
           }     
        }
        map.put(key, value);
    }
}

相关文章