Mybatis进行分页,使用limit,不能用#{},不能预编译

497 阅读1分钟

1、在MyBatis 的映射配置文件中,动态传递参数有两种方式:

(1)#{} 占位符

(2)${} 拼接符

2、#{} 和 ${} 的区别

(1)

1)#{} 为参数占位符 ?,即sql 预编译 2)${} 为字符串替换,即 sql 拼接

(2)

1)#{}:动态解析 -> 预编译 -> 执行 2)${}:动态解析 -> 编译 -> 执行

(3)

1)#{} 的变量替换是在DBMS 中 2)${} 的变量替换是在 DBMS 外

(4)

1)变量替换后,#{} 对应的变量自动加上单引号 ‘’ 2)变量替换后,${} 对应的变量不会加上单引号 ‘’

(5)

1)#{} 能防止sql 注入 2)${} 不能防止sql 注入

3、#{} 和 ${} 的实例:假设传入参数为 1

(1)开始

1)#{}:select * from t_user where uid=#{uid} 2)selectfromtuserwhereuid={}:select * from t_user where uid= ’ {uid}’

(2)然后

1)#{}:select * from t_user where uid= ? 2)${}:select * from t_user where uid= ‘1’

(3)最后

1)#{}:select * from t_user where uid= ‘1’ 2)${}:select * from t_user where uid= ‘1’

解决方案,LIMIT其实可以用#号,也可以用预编译,只不过在mapper层里 参数要提前转换成Long类型

错误示范 参数用了String,所以xml文件只能用$而不能用#


public interface UserMapper extends BaseMapper<User> {
	//参数用了String,所以xml文件只能用$而不能用#
   public List<User> findall(String pageNo, String pageSize);
}

正确的方式 参数使用Long类型,所以xml可以用#

public interface UserMapper extends BaseMapper { //参数使用Long类型,所以xml可以用# public List findall(Long pageNo, Long pageSize); }

    public interface UserMapper extends BaseMapper<User> {
	//参数用了String,所以xml文件只能用$而不能用#
   public List<User> findall(String pageNo, String pageSize);
}