博客
关于我
说说遇到的一个问题
阅读量:132 次
发布时间:2019-02-26

本文共 1584 字,大约阅读时间需要 5 分钟。

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

  

转载地址:http://xwaf.baihongyu.com/

你可能感兴趣的文章
Mysql8.0注意url变更写法
查看>>
Mysql8.0的特性
查看>>
MySQL8修改密码报错ERROR 1819 (HY000): Your password does not satisfy the current policy requirements
查看>>
MySQL8修改密码的方法
查看>>
Mysql8在Centos上安装后忘记root密码如何重新设置
查看>>
Mysql8在Windows上离线安装时忘记root密码
查看>>
MySQL8找不到my.ini配置文件以及报sql_mode=only_full_group_by解决方案
查看>>
mysql8的安装与卸载
查看>>
MySQL8,体验不一样的安装方式!
查看>>
MySQL: Host '127.0.0.1' is not allowed to connect to this MySQL server
查看>>
Mysql: 对换(替换)两条记录的同一个字段值
查看>>
mysql:Can‘t connect to local MySQL server through socket ‘/var/run/mysqld/mysqld.sock‘解决方法
查看>>
MYSQL:基础——3N范式的表结构设计
查看>>
MYSQL:基础——触发器
查看>>
Mysql:连接报错“closing inbound before receiving peer‘s close_notify”
查看>>
mysqlbinlog报错unknown variable ‘default-character-set=utf8mb4‘
查看>>
mysqldump 参数--lock-tables浅析
查看>>
mysqldump 导出中文乱码
查看>>
mysqldump 导出数据库中每张表的前n条
查看>>
mysqldump: Got error: 1044: Access denied for user ‘xx’@’xx’ to database ‘xx’ when using LOCK TABLES
查看>>