MyBatis参数计算

一、问题

前端传入参数,PageRequest.java

java
复制代码
/** * 当前页号 */ private int current = 1; /** * 页面大小 */ private int pageSize = 10;

xml文件

xml
复制代码
limit #{(current - 1) * pageSize}, #{pageSize}

报错

text
复制代码
org.mybatis.spring.MyBatisSystemException: nested exception is org.apache.ibatis.builder.BuilderException: Parsing error in {(current - 1) * pageSize} in position 14

二、解决办法

① 法一

PageRequest.java 新增属性

java
复制代码
/** * 分页起始索引(默认为0) */ private int offset = 0;

Controller中进行动态计算

java
复制代码
pageRequest.setOffset((pageRequest.getCurrent() - 1) * pageRequest.getPageSize());

xml

xml
复制代码
limit #{offset}, #{pageSize}

<bind> 标签

官方文档:https://mybatis.org/mybatis-3/zh_CN/dynamic-sql.html#bind-1

xml
复制代码
<select id="selectUserList" resultMap="UserResult"> <bind name="offset" value="(current - 1) * pageSize" /> select <include refid="selectUserVo"/> from user <where> <if test="userId != null and userId != 0">and user_id=#{userId}</if> <if test="userAccount != null and userAccount != ''">and user_account like '%${userAccount}%'</if> <if test="nickName != null and nickName != ''">and nick_name like '%#{nickName}%'</if> <if test="userRole != null and userRole != ''">and JSON_CONTAINS(user_roles, JSON_QUOTE(#{userRole}))</if> <if test="createBy != null and createBy != ''">and create_by like '%#{createBy}%'</if> <if test="updateBy != null and updateBy != ''">and update_by like '%#{updateBy}%'</if> <if test="startTime != null and endTime != null">and create_time between #{startTime} and #{endTime}</if> </where> <if test="sortField != null and sortField != ''"> ORDER BY #{sortField}, #{sortOrder} </if> limit #{offset}, #{pageSize} </select>

③ 使用 $ 字符串拼接

xml

xml
复制代码
limit ${(current - 1) * pageSize}, #{pageSize}
0个评论
点击登录,快来和大家讨论吧~
表情
图片
暂无评论
下载 APP