场景
分页查询某个角色所关联的用户信息。
map层
UserMapper
IPage<User> getByRoleId(Long roleId, IPage<User> page, @Param(Constants.WRAPPER) QueryWrapper queryWrapper);
UserMapper.xml
<select id="getByRoleId" resultType="com.example.demo.entity.User">
select * from user u
inner join user_role ur
on u.id = ur.user_id
and ur.role_id = #{roleId}
<if test="ew.sqlSegment!=null and ew.sqlSegment!=''">
and ${ew.sqlSegment}
</if>
</select>
测试
1.不带wrapper参数查询
==> Preparing: select * from user u inner join user_role ur on u.id = ur.user_id and ur.role_id = ? LIMIT ?
==> Parameters: 2(Long), 10(Long)
2.带wrapper参数查询
==> Preparing: select * from user u inner join user_role ur on u.id = ur.user_id and ur.role_id = ? and (status = ?) LIMIT ?
==> Parameters: 2(Long), 1(Integer), 10(Long)
其他补充
- Constants.WRAPPER是mybaties定义的常量"ew"
- ${ew.customSqlSegment} 会在外层套where标签,而 ${ew.sqlSegment}不会,所以使用ew.sqlSegment
- 因为wrapper可能是空的
所以要if test="ew.sqlSegment!=null and ew.sqlSegment!=''"
判断一下。否则会导致sql错误,末尾多个and