关于mybatis的$()和#()
#{}和${}的区别:
-
#{}
#{} 占位符:预编译,参数占位符 ?,防止sql注入
-
${}
${} 拼接符:编译,字符串拼接
注意事项:
order by 和 limit 和 like 的使用
order by 和 like 在使用时只能使用$()拼接符:
用 #{}会导致sql语句中多个 ’ ’ ,sql语句失效.
limit可以使用#{}
示例:
//mapper.xml文件
<mapper namespace="com.example.mapper.userMapper">
<select id="getUser" parameterType="java.lang.Long" resultType="com.example.pojo.UserEntity">
select * from users2dl where id=#{id}
</select>
<select id="selectBylimit2" resultType="com.example.pojo.UserEntity">
SELECT * FROM users2dl ORDER BY ${data} desc LIMIT #{startIndex},#{pageSize}
</select>
</mapper>
//mapper接口文件
public interface userMapper {
List<UserEntity> selectBylimit2(@Param("data")String data,@Param("startIndex")int startIndex,@Param("pageSize")int pageSize);
UserEntity getUser(Long id);
}
执行结果:
如上图可以看出, #{}会导致sql语句中多个 ’ ’ ,sql语句失效。
-
当使用 ${}符时mybatis执行的语句为:
SELECT * FROM users2dl order by id desc limit 1,3; -
当使用 #{}符时mybatis执行的语句为:
SELECT * FROM users2dl order by ‘id’ desc limit 1,3;