本文面向初学者和小白,介绍QueryWrapper和UpdateWrapper的简单使用。
QueryWrapper和UpdateWrapper都是mybatis-plus中Wrapper类的子类,用于构造SQL条件语句,QueryWrapper用于查询语句中,UpdateWrapper用于更新或删除语句中。
注:本文示例基于Springboot框架

实体(model)类:图书类型

// 实体类 图书类型
public class BookType {
    @TableId(value = "type_id", type = IdType.AUTO)
    private Integer typeId;// 类型ID
    private Integer parentId;// 父类型ID
    private String typeName;// 类型名称 例如科幻类...
}

一、QueryWrapper示例

Service层

通过QueryWrapper等效实现以下sql语句
SELECT * FROM book_type WHERE parent_id<>0 AND type_id>4 OR type_id<2

@Service
public class BookTypeServiceImpl extends ServiceImpl<BookTypeDao, BookType> implements BookTypeService {

    @Resource
    private BookTypeDao bookTypeDao;

    // 演示条件查询 使用QueryWrapper<>
    public List<BookType> finds(){
    	// 1.创建条件构造器 泛型为数据库表对应model类
        QueryWrapper<BookType> wrapper = new QueryWrapper<>();
        // 2.设置查询条件:ne不等于 ge大于 or或者 lt小于
        wrapper.ne("parent_id", 0).ge("type_id", 4).or().lt("type_id", 2);
        // 3.使用条件构造器
        List<BookType> bookTypes = bookTypeDao.selectList(wrapper);
        return bookTypes;
    }
}

二、UpdateWrapper示例

Service层

通过UpdateWrapper等效实现以下sql语句
DELETE FROM book_type WHERE type_id=8;

@Service
public class BookTypeServiceImpl extends ServiceImpl<BookTypeDao, BookType> implements BookTypeService {

    @Resource
    private BookTypeDao bookTypeDao;

    // 演示条件删除 使用UpdateWrapper<>
    public Integer wrapperDel(){
    	// 1.创建条件构造器 泛型为数据库表对应model类
        UpdateWrapper<BookType> wrapper = new UpdateWrapper<>();
        // 2.设置查询条件:eq 等于
        wrapper.eq("type_id", 8);
        // 3.使用条件构造器
        Integer rows = bookTypeDao.delete(wrapper);
        return rows;
    }
}

详细用法可参考:mybatis-plus中wrapper的用法

Logo

魔乐社区(Modelers.cn) 是一个中立、公益的人工智能社区,提供人工智能工具、模型、数据的托管、展示与应用协同服务,为人工智能开发及爱好者搭建开放的学习交流平台。社区通过理事会方式运作,由全产业链共同建设、共同运营、共同享有,推动国产AI生态繁荣发展。

更多推荐