SpringBoot - MyBatis-Plus - 如何在查询时排除某些字段?
作者:mmseoamin日期:2023-12-20

写在前面

查询时部分字段不想给前端显示,怎么办?

(1)使用SELECT方法,排除字段"password"
@Override
public Page list(String name, Integer status, Integer pageNo, Integer limit, Long adminId) throws ServiceException {
    QueryWrapper wrapper = new QueryWrapper<>();
    if (!ObjectUtils.isEmpty(name)) {
        wrapper.like("name", name);
    }
    if (status != null) {
        wrapper.eq("status", status);
    }
    wrapper.select(UserDO.class, user -> !user.getColumn().equals("password") && !user.getColumn().equals("salary"));
    wrapper.orderByDesc("id");
    return userMapper.selectPage(Page.div(pageNo, limit, UserDO.class), wrapper);
}
// 生成的SQL语句为:
SELECT id,presenter,qq,wx,mail,name,id_no,id_card_front,id_card_back,phone,
salt,ali_mp_open_id,wx_mp_open_id,wx_h5_open_id,wx_app_open_id,nickname,
avatar_url,province,city,county,level,gmt_vip_expire,birthday,gender,gmt_last_login,
last_login_ip,status,gmt_update,gmt_create 
FROM mcsx_user ORDER BY id DESC LIMIT ?
(2)使用SELECT方法,只显示某些字段
@Override
public Page list(String name, Integer status, Integer pageNo, Integer limit, Long adminId) throws ServiceException {
    QueryWrapper wrapper = new QueryWrapper<>();
    if (!ObjectUtils.isEmpty(name)) {
        wrapper.like("name", name);
    }
    if (status != null) {
        wrapper.eq("status", status);
    }
    wrapper.select("id", "name", "level", "qq", "wx", "gmt_last_login");
    wrapper.orderByDesc("id");
    return userMapper.selectPage(Page.div(pageNo, limit, UserDO.class), wrapper);
}
// 生成的SQL语句为:
SELECT id,name,level,qq,wx,gmt_last_login FROM mcsx_user ORDER BY id DESC LIMIT ?
(3)使用@TableField(exist = false),排除某些字段

注:表示当前属性不是数据库的字段,但在项目中必须使用,这样的话在新增/查询等使用BEAN时,MyBatis-Plus都会忽略这个属性,所以推荐使用方法1和方法2。

@Data
@ApiEntity(description = "用户领域模型表")
@TableName("mcsx_user")
public class UserDO extends SuperDO {
    @ApiField(description = "推荐者")
    private Long presenter;
    @TableField(exist = false)
    @ApiField(description = "QQQQ号")
    private String qq;
    @TableField(exist = false)
    @ApiField(description = "微信号")
    private String wx;
    @ApiField(description = "电子邮箱")
    private String mail;
    @ApiField(description = "姓名")
    private String name;
    @ApiField(description = "身份证号")
    private String idNo;
    
    ...
}
// 生成的SQL语句为:
SELECT id,presenter,mail,name,id_no,id_card_front,id_card_back,phone,
salt,ali_mp_open_id,wx_mp_open_id,wx_h5_open_id,wx_app_open_id,nickname,
avatar_url,province,city,county,level,gmt_vip_expire,birthday,gender,gmt_last_login,
last_login_ip,status,gmt_update,gmt_create FROM mcsx_user ORDER BY id DESC LIMIT ?