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

你可能感兴趣的文章
Webpack 之 basic chunk graph
查看>>
Mysql5.7版本单机版my.cnf配置文件
查看>>
mysql5.7的安装和Navicat的安装
查看>>
mysql5.7示例数据库_Linux MySQL5.7多实例数据库配置
查看>>
Mysql8 数据库安装及主从配置 | Spring Cloud 2
查看>>
mysql8 配置文件配置group 问题 sql语句group不能使用报错解决 mysql8.X版本的my.cnf配置文件 my.cnf文件 能够使用的my.cnf配置文件
查看>>
MySQL8.0.29启动报错Different lower_case_table_names settings for server (‘0‘) and data dictionary (‘1‘)
查看>>
MYSQL8.0以上忘记root密码
查看>>
Mysql8.0以上重置初始密码的方法
查看>>
mysql8.0新特性-自增变量的持久化
查看>>
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
查看>>