说说遇到的一个问题
2017-01-09 14:09
155 查看
在周末的解决上线系统中的bug中,首先说一下我们采用的是mybatis,由于我自己写的一个方法出现了排序没法排序的问题,我是把排序字段需要作为参数传进去,结果发现排序失效了,解决了半天解决了,我们老大用了个if对排序字段转换了一下,附上最原始的有问题的那个sql,
<select id="selectBycatid" resultType="Product" >
SELECT
<include refid="Base_Column_List" />
from product
where create_date=#{getdate} and cat_id=#{catid}
order by #{orderstr} DESC
limit 0,#{tops}
</select>
这个问题我看了一些,想起以前也用ibatis插件生成过数据库的配置,记得order by 字段 ,这个字段用的是${},中午试了一下,自己写了个例子发现,这个就该用${}这样,否则就没法正常排序。改后的sql 为:
<select id="selectBycatid" resultType="Product" >
SELECT
<include refid="Base_Column_List" />
from product
where create_date=#{getdate} and cat_id=#{catid}
order by ${orderstr} DESC
limit 0,#{tops}
</select>
这样问题就解决了。这里简单记录一下#{}与${}的区别:看到某人的博客中找到的mybatis的解释,感觉挺好,直接拿来用一下,官网的解释:
从这段文字我们看出#{}属于预编译,比较安全,采用${}的变量,mybatis 不修改也不进行转义,也说明了order by 要用${}而不能用#{},这也就说明了这个问题,例如动态表名是参数的这种也要用${}不能用#{},写的还是太简单,文中有问题希望不吝赐教。
<select id="selectBycatid" resultType="Product" >
SELECT
<include refid="Base_Column_List" />
from product
where create_date=#{getdate} and cat_id=#{catid}
order by #{orderstr} DESC
limit 0,#{tops}
</select>
这个问题我看了一些,想起以前也用ibatis插件生成过数据库的配置,记得order by 字段 ,这个字段用的是${},中午试了一下,自己写了个例子发现,这个就该用${}这样,否则就没法正常排序。改后的sql 为:
<select id="selectBycatid" resultType="Product" >
SELECT
<include refid="Base_Column_List" />
from product
where create_date=#{getdate} and cat_id=#{catid}
order by ${orderstr} DESC
limit 0,#{tops}
</select>
这样问题就解决了。这里简单记录一下#{}与${}的区别:看到某人的博客中找到的mybatis的解释,感觉挺好,直接拿来用一下,官网的解释:
String Substitution By default, using the #{} syntax will cause MyBatis to generate PreparedStatement properties and set the values safely against the PreparedStatement parameters (e.g. ?). While this is safer, faster and almost always preferred, sometimes you just want to directly inject a string unmodified into the SQL Statement. For example, for ORDER BY, you might use something like this: ORDER BY ${columnName} Here MyBatis won't modify or escape the string. NOTE It's not safe to accept input from a user and supply it to a statement unmodified in this way. This leads to potential SQL Injection attacks and therefore you should either disallow user input in these fields, or always perform your own escapes and checks.
从这段文字我们看出#{}属于预编译,比较安全,采用${}的变量,mybatis 不修改也不进行转义,也说明了order by 要用${}而不能用#{},这也就说明了这个问题,例如动态表名是参数的这种也要用${}不能用#{},写的还是太简单,文中有问题希望不吝赐教。
相关文章推荐
- 说说自己遇到的一个问题
- 配置Struts连接池时遇到的一个问题
- SimpleDateFormt 使用中遇到的一个小问题
- 使用css expression遇到的一个问题
- 编VC网络程序遇到一个问题,原来是少了一个LIB。
- [导入]遇到一个麻烦的问题
- 今天又遇到了一个问题
- [存档]工作中遇到的一个SqlServer2000中大数据量表的检索问题
- 昨天下午遇到一个问题,到晚上才解决。
- 安装 Visual Stdio.net 2003 时遇到的一个问题
- 今天又遇到了一个问题
- 在使用BizTalk时遇到一个很郁闷的问题 之解决篇
- 今天遇到一个关于STL中排序的问题, 怀疑是sort的bug!
- 关于这两天遇到的一个问题
- [导入]ASP.NET 2.0 的内部变化+金山词霸遇到的一个问题
- 在使用BizTalk时遇到一个很郁闷的问题
- 刚刚转入C#,遇到一个疑惑的问题
- 今天遇到的一个关于HttpSessionListener 的一个问题
- 今天用 hbm2ddl 生成数据库脚本时,不明不白地遇到了一个问题又糊里糊涂解决了
- 遇到一个问题,在rcp里不能连接上去