Title

Mybatis慢查询问题

一、问题

使用Mybatis查询数据库数据时发现,时间跨度大且数据量多的情况下,查询速度变得十分慢,120s以上
然而将sql语句放至数据库中去查询时速度很快,只在10s左右
带两个时间条件的情况下,最慢
任意一个时间或者不带时间次之

二、Mybatis中的sql

select h.SBDW_ID, h.SBDW ,count(distinct SBR_ID) as countNumber,'hcrs' as statisticType
        from  zfapp_dsj_HCXX h
        <where>
            h.ENABLE_FLAG = 1 and h.DEL_FLAG = 0 and h.zt='1' and exists (select 1 from T_USER_POST t,T_USER u,T_POST p where t.post_id=p.id and u.id=t.user_id  and   u.id = h.SBR_ID
            and p.department_id = h.sbdw_id and u.status = 0)
            <if test="searchModel !=null and searchModel.hcStartTime != null">
                and h.SBSJ &gt;= #{searchModel.hcStartTime}
            </if>
            <if test="searchModel !=null and searchModel.hcEndTime != null">
                and h.SBSJ &lt; #{searchModel.hcEndTime}+1
            </if>
            <if test="searchModel != null and searchModel.departmentId != null and searchModel.departmentId.length > 0">
                and h.SBDW_ID in
                <foreach collection="searchModel.departmentId" item="dep" open="(" separator="," close=")">
                    #{dep}
                </foreach>
            </if>

        </where>
        group by h.SBDW_ID, h.SBDW
union
  ...

至少有19个这样的语句拼接到一起

三、分析

在将

#{searchModel.hcStartTime}

修改为

to_date('${searchModel.hcStartTime}', 'yyyy-MM-dd')

后速度和数据库中执行的速度一致;

推测原因可能是因为mybatis将#{}作为占位符进行预编译,在参数类型与数据库字段类型不匹配的时候会对参数进行类型处理,导致时间变慢

但是为什么数据量小的时候速度并不慢?

四、解决方案

1、临时解决方案:
1)使用java.sql.date接收日期参数,并对日期参数进行校验防止sql注入;
2)将#{}改为${},并使用oracle的to_date函数进行转换

posted @   Jackpot_ABC  阅读(859)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 单元测试从入门到精通
· 上周热点回顾(3.3-3.9)
· winform 绘制太阳,地球,月球 运作规律
点击右上角即可分享
微信分享提示