转自:
MyBatis中的$和#,你知道他们的区别吗?
下文笔者将讲述MyBatis中的$和#的区别简介说明,如下所示:
在MyBatis的xml配置文件中
我们经常看见$和#后面紧跟变量,那么他们有什么区别呢?
下文笔者将一一道来,如下所示:
1.#{ }是预编译处理
MyBatis在处理#{ }时,它会将sql中的#{ }替换为?
然后调用PreparedStatement的set方法来赋值,传入字符串后,会在值两边加上单引号
2.#{} MyBatis在处理时,直接采用字符串替换的方式
注意事项:
使用${ }会导致sql注入
不利于系统的安全性
例:
<select id="selectPostList" parameterType="SysPost" resultMap="SysPostResult">
<include refid="selectPostVo"/>
<where>
<if test="postCode != null and postCode != ''">
AND post_code like concat('%', #{postCode}, '%')
</if>
<if test="status != null and status != ''">
AND status = #{status}
</if>
<if test="postName != null and postName != ''">
AND post_name like concat('%', #{postName}, '%')
</if>
</where>
</select>