MyBatis-Plus 使用wrapper自定义SQL

工作中需要在查询的内容中多一个字段属性方便前端操作,但是这个属性是其他表的,本来使用的是wrapper条件构造器,然后通过list(wrapper)能很方便的查询出数据集,但是现在要连表查询了,其中这个查询还有很多的其他操作,因此选择使用wrapper结合sql一起使用来进行查询。

第一步:

在mapper文件中定义方法,方法的参数为

@Param(Constants.WRAPPER) Wrapper wrapper

List<ResultDataDTO> selectData(@Param(Constants.WRAPPER) Wrapper<ResultDataDTO> wrapper);

第二步:

修改mapper文件,添加上新的select,并在sql的最后添加上  ${ew.customSqlSegment}

<select id="selectData" resultType="com.test.dto.ResultDataDTO">
        SELECT a.*,
        b.DeviceName
        FROM 表1 a
        INNER JOIN 表2 b
        ON a.DeviceNum = b.DeviceNum ${ew.customSqlSegment}
</select>

第三步:

测试结果:

注意,如果wrapper中传入的字段在查询的多个表中存在,那么要带上前缀,即下面代码中的a.DeviceNum,这个a对应xml文件中的那个表的别名a。如果没有这样的话,会爆

column in where clause is amiguous

    @Test
    public void test(){
        QueryWrapper<ResultDataDTO> wrapper = new QueryWrapper<>();
        wrapper.eq("a.DeviceNum", "30");
        
        xxxMapper.selectData(wrapper);
    }


版权声明:本文为hk1052606583原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。