写接口:6个
遇到的问题:
在stock-info层写动态sql时:场面一度尴尬,不过睡了一觉就解决了。问题是之前一直使用#{},而#{}传入的参数是带引号的,我们这里用的是字段名,不需要引号,所以使用${}就OK了
<!--查找最大%升幅-->
<select id="findMaxUpChangedPercent" resultMap="BaseResultMap" parameterType="com.simnectzbank.lbs.systemlayer.stockinfo.entity.StockInformationEntity" >
select * from StockInformation
where 1=1
<if test="indexComponent != null and indexComponent !=''">
and ${indexComponent} = 'Y'
</if>
order by ChangedPercent desc
<if test="start >= 0 and end > 0">
limit #{start},#{end}
</if>
</select>
<!--查找最大%跌幅-->
<select id="findMaxDownChangedPercent" resultMap="BaseResultMap" parameterType="com.simnectzbank.lbs.systemlayer.stockinfo.entity.StockInformationEntity" >
select * from StockInformation
where ChangedPercent < 0
<if test="indexComponent != null and indexComponent !=''">
and ${indexComponent} = 'Y'
</if>
order by ChangedPercent desc
<if test="start >= 0 and end > 0">
limit #{start},#{end}
</if>
</select>
关键点在于:${}和#{}的区别:
${ } 的变量的替换阶段是在动态 SQL 解析阶段,而 #{ }的变量的替换是在 DBMS 中。
#{}与${}的区别可以简单总结如下:
- #{}将传入的参数当成一个字符串,会给传入的参数加一个双引号
- ${}将传入的参数直接显示生成在sql中,不会添加引号
- #{}能够很大程度上防止sql注入,${}无法防止sql注入
应用:
- ${}在预编译之前已经被变量替换了,这会存在sql注入的风险。
- ${}一般用于传输数据库的表名、字段名等
- 能用#{}的地方尽量别用${}