有order by 中的传值引起的问题:order by 后面不能用# 只能用$ 进行传值
<select id="queryServerPage" resultType="io.sportii.common.entity.pension.ServerEntity">
SELECT
id,
id as server_id,
name,
name as server_name,
photo,
dept_id,
display,
(select d.value from sys_dict d where d.type='isdisplay' and d.code=pension_server.display) as display_name,
business_id,
(select name from sys_business where id=pension_server.business_id) as business_name,
type,
(select d.value from sys_dict d where d.type='serverType' and d.code=pension_server.type) as type_name,
scale_price,
scale_id,
(select scale_unit from pension_server_fee_scale scale where scale.id=pension_server.scale_id) as scale_unit,
server_category_id,
(SELECT c.`name` FROM pension_server_category c WHERE c.category_id=pension_server.server_category_id) as server_category_name,
create_date
FROM
pension_server
WHERE 1=1
<if test="display != null and '' != display ">
and display = #{display}
</if>
<if test="serverCategoryId != null and '' != serverCategoryId ">
and server_category_id = #{serverCategoryId}
</if>
<if test="type != null and '' != type ">
and type = #{type}
</if>
<if test="serverNameOr != null and '' != serverNameOr ">
and name like concat('%',#{serverNameOr},'%')
</if>
<if test="dept_auth != null and dept_auth.size()>0">
and dept_id in
<foreach item="deptId" index="index" collection="dept_auth" open="(" separator="," close=")">
#{deptId}
</foreach>
</if>
<choose>
<when test="sidx != null and ''!= sidx">
ORDER BY ${sidx} Asc
</when>
<otherwise>
ORDER BY create_date DESC
</otherwise>
</choose>
1. #将传入的数据都当成一个字符串,会对自动传入的数据加一个双引号。如:order by #user_id#,如果传入的值是111,那么解析成sql时的值为order by "111", 如果传入的值是id,则解析成的sql为order by "id".
2. $将传入的数据直接显示生成在sql中。如:order by $user_id$,如果传入的值是111,那么解析成sql时的值为order by user_id, 如果传入的值是id,则解析成的sql为order by id.
3. #方式能够很大程度防止sql注入。
4.$方式无法防止Sql注入。
5.$方式一般用于传入数据库对象,例如传入表名.
6.一般能用#的就别用$.
MyBatis排序时使用order by 动态参数时需要注意,用$而不是#
字符串替换
默认情况下,使用#{}格式的语法会导致MyBatis创建预处理语句属性并以它为背景设置安全的值(比如?)。这样做很安全,很迅速也是首选做法,有时你只是想直接在SQL语句中插入一个不改变的字符串。比如,像ORDER BY,你可以这样来使用:
ORDER BY ${columnName}
这里MyBatis不会修改或转义字符串。
重要:接受从用户输出的内容并提供给语句中不变的字符串,这样做是不安全的。这会导致潜在的SQL注入攻击,因此你不应该允许用户输入这些字段,或者通常自行转义并检查。
ps:在使用mybatis中还遇到<![CDATA[]]>的用法,在该符号内的语句,将不会被当成字符串来处理,而是直接当成sql语句,比如要执行一个存储过程。