博客
关于我
说说遇到的一个问题
阅读量: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/

你可能感兴趣的文章
mysql 内连接、自然连接、外连接的区别
查看>>
mysql 写入慢优化
查看>>
mysql 分组统计SQL语句
查看>>
Mysql 分页
查看>>
Mysql 分页语句 Limit原理
查看>>
MySql 创建函数 Error Code : 1418
查看>>
MySQL 创建新用户及授予权限的完整流程
查看>>
mysql 创建表,不能包含关键字values 以及 表id自增问题
查看>>
mysql 删除日志文件详解
查看>>
mysql 判断表字段是否存在,然后修改
查看>>
MySQL 到底能不能放到 Docker 里跑?
查看>>
mysql 前缀索引 命令_11 | Mysql怎么给字符串字段加索引?
查看>>
MySQL 加锁处理分析
查看>>
mysql 协议的退出命令包及解析
查看>>
mysql 参数 innodb_flush_log_at_trx_commit
查看>>
mysql 取表中分组之后最新一条数据 分组最新数据 分组取最新数据 分组数据 获取每个分类的最新数据
查看>>
MySQL 命令和内置函数
查看>>
MySQL 和 PostgreSQL,我到底选择哪个?
查看>>
mysql 四种存储引擎
查看>>
MySQL 在并发场景下的问题及解决思路
查看>>