情景:
sql语句 查询大数据量时:
sql语句在plsql 上执行非常快,放到java上mybatis 上执行 非常的慢,甚至时间超时;
此种问题是 oralce数据库类型自动隐式转换导致没走索引:
在mybatis中如果使用的是#,拼接后参数带引号
where aa.enter_time >= #{startTime} and aa.enter_time <= #{endTime} 或 where aa.enter_time >= #{startTime,jdbcType =timestamp } and aa.enter_time <= #{endTime,jdbcType =timestamp }
大数据量查询执行时会自动隐式转换,变为 to_timestamp(aa.enter_time) >= #{startTime,jdbcType =timestamp }
此时 查询不会走数据库上的enter_time字段的索引,所以查询效率非常慢;
解决方法:
1.将传入参数改为String 在mybatis 使用 to_date 进行拼接:
where aa.enter_time >= to_date(#{startTime}, 'yyyy-MM-dd hh24:mi:ss')
and aa.enter_time <= to_date(#{endTime}, 'yyyy-MM-dd hh24:mi:ss')
2.将#改为$ , 详细可看#与$区别,这个改法主要使用 '
where aa.enter_time >= '${startTime}'
and .....
3. 在#{}后+0:这样不会让oracle 进行隐式转换,走索引查询
where aa.enter_time >= #{startTime}+0 and aa.enter_time <= #{endTime}+0