mybatis 查询返回结果封装成map而不是

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/weixin_37885641/article/details/83749557

一、背景
最近项目中有个导出excel缓慢,数据量也不是很大,每次限制5000条,sql查询很快,问题出现在把数据库中的原因代号转化为字符串的过程。原代码是把查询出来的结果进行for循环,然后一个个的根据reasonId去查数据库,再把结果set到bean中,导致非常缓慢。

二、优化策略
优化的策略是一次把结果查询出来,然后存储到map中,以reasonId作为key,reasonBean作为value,如Map<Long,reasonBean>这种。因为reasonBean的主键是reasonId为Long类型的,所以map中的key就是Long类型的。然后在写入到excel中时,原因的字段值直接根据reasonId从map中get就可以了,速度很快。

三、例子
xml文件:

<select id="selectAllReason" resultType="ReasonBean">
	 select REASON_ID reasonId,REASON_NAME reasonName from xxx
	</select>

dao层:

public Map<Long,ReasonBean> selectAllReason() {
		return sqlsession.selectMap("xxxxx.selectAllReason", "reasonId");
	}
	(项目中使用的不是接口,而是实现类中注入了sqlsession,使用selectMap方法)

service层:

Map<Long, ReasonBean> reasonMap = this.xxxDao.selectAllReason();
查询出的结果就以reasonId为key,reasonBean为value

猜你喜欢

转载自blog.csdn.net/weixin_37885641/article/details/83749557
今日推荐