ew是mapper方法里的@Param(Constants.WRAPPER) Wrapper queryWrapper对象
首先判断ew.emptyOfWhere是否存在where条件,有的话再拼接上去,ew.customSqlSegment是WHERE + sql语句
没有where的时候加上 == false
使用${ew.sqlSegment} 如果是连表查询且查询条件是连表的字段则需在service层拼接查询条件时字段前指定别名
最佳例子1
mapper.xml
<select id="tableList" resultType="java.util.LinkedHashMap"> SELECT ${ew.sqlSelect} // 这里拼接select后面的语句 FROM ${table_name} //如果是单表的话,这里可以写死 ${ew.customSqlSegment} </select>
mapper
IPage<LinkedHashMap<String,Object>> tableList(@Param("table_name") String table_name, Page page, @Param(Constants.WRAPPER) QueryWrapper queryWrapper);
test
String responseField = "*"; queryWrapper.select(responseField); // 即 select * ... String responseField = "name"; queryWrapper.select(responseField); // 即 select name ...
最佳例子2
controller
public String saveAddress(HttpSession session) { UserVO user1 = (UserVO)session.getAttribute("user"); LambdaQueryWrapper<User> lambdaQueryWrapper = Wrappers.<User>lambdaQuery() .select(User::getNickName, User::getUserId) // 需要查询的列,即 ${ew.sqlSelect} .eq(User::getUserId, user1.getUserId());// 条件 User user = this.userMapper.selectNickNameAndUserId(lambdaQueryWrapper); System.out.println(user); return null; }
mapper
User selectNickNameAndUserId(@Param(Constants.WRAPPER) LambdaQueryWrapper<User> queryWrapper);
mapper.xml
<select id="selectNickNameAndUserId" resultType="com.example.demo.entity.User"> select <if test="ew != null and ew.SqlSelect != null and ew.SqlSelect != ''"> ${ew.SqlSelect} </if> from user where is_deleted != 1 <if test="ew != null"> <if test="ew.nonEmptyOfWhere"> AND </if> ${ew.sqlSegment} </if> </select> <select id="selectNickNameAndUserId" resultType="com.example.demo.entity.User"> select <if test="ew != null and ew.SqlSelect != null and ew.SqlSelect != ''"> ${ew.SqlSelect} </if> from user ${ew.customSqlSegment} </select>
使用${ew.sqlSegment} 如果是联表查询且查询条件是连表的字段则需在service层拼接查询条件时字段前指定别名,而且不能用lambda的查询了
<select id="selectByRoleId" resultType="com.captain.crewer.mybatis.plus.dto.RolePermsDTO"> SELECT tp.id, tp.perm_name, tp.url, tr.role_id as roleId, tr.role_name as roleName FROM tb_role tr LEFT JOIN tb_perm_role tpr ON tr.role_id = tpr.role_id LEFT JOIN tb_perm tp ON tpr.perm_id = tp.id ${ew.customSqlSegment} </select>
mapper
List<RolePermsDTO> selectByRoleId(@Param(Constants.WRAPPER) Wrapper<RolePermsDTO> wrapper); @Test public void test2(){ QueryWrapper<RolePermsDTO> wrapper = new QueryWrapper<>(); wrapper.eq("tr.role_id", 1); tbPermService.selectByRoleId(wrapper); }