MyBatis动态排序问题

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/skygm/article/details/68924160

在使用MyBatis时加入来按指定字段进行排序

  ORDER BY
    	<choose>
    	<when test="sort!=null">
    			#{sort,jdbcType=VARCHAR}
    		<if test="order!=null">
    		 	#{order,jdbcType=VARCHAR}
    		</if>
    	</when>
    	<otherwise>
    		id asc , create_time asc
    	</otherwise>
     </choose>

执行后,加入的排序无效
原因是: #{order,jdbcType=VARCHAR}, MyBatis会创建预编译的语句,然后为它设置相应的值.MyBatis会自动将排序字段当成一个字符串,等同于order by 'create_time' 'desc',可以通过执行,但无效,与order by create_time desc结果不同
解决方法:使用${order},Mybatis会将其视作直接变量,变量替换成功后,不会再加上引号成为字符串,同样排序顺序也一样${order},因此修改如下

  ORDER BY
    	<choose>
    	<when test="sort!=null">
    			${sort}
    		<if test="order!=null">
    		 	${order}
    		</if>
    	</when>
    	<otherwise>
    		id asc , create_time asc
    	</otherwise>
     </choose>

注:
#能很大程度的防止SQL注入
$无法防止Sql注入
$用于传入数据库对象
<![CDATA[]]>,在该符号内的语句,不会被当成字符串来处理,而是直接当成sql语句,比如要执行一个存储过程。在mapper文件中写sql语句时,遇到特殊字符时,如:< > 等,建议使用<![CDATA[ sql 语句 ]]>标记,将sql语句包裹住,不被解析器解析

猜你喜欢

转载自blog.csdn.net/skygm/article/details/68924160