mybatis-plus 通过QueryWrapper进行多条件查询

标题mybatis-plus QueryWrapper

pojo:

@Data
@EqualsAndHashCode(callSuper = false)
@Accessors(chain = true)
@TableName("m_goods")
@ApiModel(value="Goods对象", description="")
public class Goods implements Serializable {

    private static final long serialVersionUID = 1L;

    @ApiModelProperty(value = "序号主键")
    @TableId(value = "id", type = IdType.AUTO)
    private Integer id;

    @ApiModelProperty(value = "货物名称")
    private String goodsname;

    @ApiModelProperty(value = "货物价格")
    private Integer goodsprice;

    @ApiModelProperty(value = "货物数量")
    private Integer goodsnum;
}

Controller:

@ApiOperation(value = "根据条件查询商品")
    @PostMapping("/selectGoodsByCondition/{currentPage}/{pageSize}")
    public RespBean selectGoodsByCondition(@RequestBody Goods goods, @PathVariable("currentPage") Integer currentPage, @PathVariable("pageSize") Integer pageSize) {
        return goodsService.selectGoodsByCondition(goods, currentPage, pageSize);
    }

service:

@Override
    public RespBean selectGoodsByCondition(Goods goods,int currentPage, int pageSize) {
        QueryWrapper queryWrapper = isConditon(goods);
        PageHelper.startPage(currentPage, pageSize);
        List<Goods> goodsList = goodsMapper.selectGoodsByCondition(queryWrapper);
        return RespBean.success("查询成功", goodsList);
    }

构建查询条件:

/**
     * 查询条件构建
     * @param goods
     * @return
     */
    private QueryWrapper isConditon(Goods goods) {
        QueryWrapper queryWrapper = new QueryWrapper();
        if (goods != null) {
            if (!goods.getGoodsname().isEmpty()) {
                queryWrapper.like("goodsname", goods.getGoodsname());
            }
            if (goods.getGoodsnum() != null) {
                queryWrapper.eq("goodsnum", goods.getGoodsnum());
            }
            if (goods.getGoodsprice() != null) {
                queryWrapper.eq("goodsprice", goods.getGoodsprice());
            }
        }
        return queryWrapper;
    }

mapper:

public interface GoodsMapper extends BaseMapper<Goods> {

    List<Goods> selectGoodsByCondition(@Param(Constants.WRAPPER) Wrapper queryWrapper);
}

xml:

<select id="selectGoodsByCondition" resultType="com.xxx.pojo.Goods">
        select * from m_goods
        <if test="ew.emptyOfWhere == false">
            ${ew.customSqlSegment}
        </if>
    </select>

ew是mapper方法里的@Param(Constants.WRAPPER) Wrapper queryWrapper对象,Constants.WRAPPER的值就是ew。
首先判断ew.emptyOfWhere是否存在where条件,有的话再拼接上去。
ew.customSqlSegment是WHERE + sql语句。

你可能感兴趣的:(mybatis,mysql,java,spring)