对数据库的查询往往会消耗比较大的资源,因此我们在写代码的时候会侧重于在代码里去完成实体类的聚合而不是通过不断的查询。
最近在review code的时候发现了在遍历列表的循环查询数据库是十分消耗资源的。因此来考虑用更高效的方式去解决这个问题。
下面是问题:
List<Long> locationList = locationGroupInfo.getLocationList();
if(locationList != null && locationList.size() != 0) {
Long groupId = adLocationGroup.getId();
List<AdLocationAdLocationGroup> adLocationAdLocationGroupList = new ArrayList<AdLocationAdLocationGroup>();
for(Long id : locationList) {
AdLocationAdLocationGroup adLocationAdLocatioGroup = new AdLocationAdLocationGroup();
adLocationAdLocatioGroup.setAdId(id);
adLocationAdLocatioGroup.setLocationGroupId(groupId);
adLocationAdLocationGroupMapper.insertSelective(adLocationAdLocationGroup);
}
}
这样对数据库插入的太频繁,因此需要改进。我们找到能够批量插入的mybaits支持,定义mapper:listCRUDMapper,当中定义接口:
// 批量插入AdLocationAdLocationGroup
public int insertAdLocationAdLocationGroupList(List<AdLocationAdLocationGroup> adLocationAdLocationGroupList);
sqlmap:
<insert id="insertAdLocationAdLocationGroupList" parameterType="java.util.List">
<selectKey resultType="java.lang.Long" keyProperty="id"
order="AFTER">
SELECT LAST_INSERT_ID()
</selectKey>
insert into ad_location_ad_location_group (id, ad_id,
location_group_id
)
values
<foreach collection="list" item="adLocationAdLocationGroup"
index="index" separator=",">
(#{adLocationAdLocationGroup.id,jdbcType=BIGINT},
#{adLocationAdLocationGroup.adId,jdbcType=BIGINT},
#{adLocationAdLocationGroup.locationGroupId,jdbcType=BIGINT}
)
</foreach>
</insert>
优化后的代码:
List<Long> locationList = locationGroupInfo.getLocationList();
if(locationList != null && locationList.size() != 0) {
Long groupId = adLocationGroup.getId();
List<AdLocationAdLocationGroup> adLocationAdLocationGroupList = new ArrayList<AdLocationAdLocationGroup>();
for(Long id : locationList) {
AdLocationAdLocationGroup adLocationAdLocatioGroup = new AdLocationAdLocationGroup();
adLocationAdLocatioGroup.setAdId(id);
adLocationAdLocatioGroup.setLocationGroupId(groupId);
adLocationAdLocationGroupList.add(adLocationAdLocatioGroup);
}
listCRUDMapper.insertAdLocationAdLocationGroupList(adLocationAdLocationGroupList);
}
这样不用遍历的每次都去操纵数据库。提高了效率。