您的位置:首页 > 其它

说说遇到的一个问题

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的解释,感觉挺好,直接拿来用一下,官网的解释:

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 要用${}而不能用#{},这也就说明了这个问题,例如动态表名是参数的这种也要用${}不能用#{},写的还是太简单,文中有问题希望不吝赐教。

  
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: