MybatisPlus入门实践
简介
Mybatis-Plus 简称 MP ,是 Mybatis 的增强工具,提供了一批开箱即用的功能、特性、接口、注解,简化了应用程序访问数据库的相关操作,完善了Mybatis作为ORM仅能做到半自动的不足,提高了开发人员的开发效率。
MP是社区产品,当前源代码在Github上面进行维护,基于Apache2.0开源协议,可放心在商业项目上使用。 常用注解TableName:表名注解,标识实体类对应的数据库表 TableId:主键注解,标识此属性对应数据库中的主键字段 TableField:字段注解(非主键) CRUD接口
MP的宗旨就是简化编码,所以一般而言,都是尽量直接使用 service 层接口。若确需手写 sql , 在 mapper 层中编写注解,当然也可以编写xml,更加推荐注解方式,因为xml方式下类型推导和引用会失效。
以下内容摘抄自官网 Service层接口save// 插入一条记录(选择字段,策略插入) boolean save(T entity); // 插入(批量) boolean saveBatch(Collection entityList); // 插入(批量) boolean saveBatch(Collection entityList, int batchSize);saveOrUpdate// TableId 注解存在更新记录,否插入一条记录 boolean saveOrUpdate(T entity); // 根据updateWrapper尝试更新,否继续执行saveOrUpdate(T)方法 boolean saveOrUpdate(T entity, Wrapper updateWrapper); // 批量修改插入 boolean saveOrUpdateBatch(Collection entityList); // 批量修改插入 boolean saveOrUpdateBatch(Collection entityList, int batchSize);remove// 根据 entity 条件,删除记录 boolean remove(Wrapper queryWrapper); // 根据 ID 删除 boolean removeById(Serializable id); // 根据 columnMap 条件,删除记录 boolean removeByMap(Map columnMap); // 删除(根据ID 批量删除) boolean removeByIds(Collection<? extends Serializable> idList);update// 根据 UpdateWrapper 条件,更新记录 需要设置sqlset boolean update(Wrapper updateWrapper); // 根据 whereWrapper 条件,更新记录 boolean update(T updateEntity, Wrapper whereWrapper); // 根据 ID 选择修改 boolean updateById(T entity); // 根据ID 批量更新 boolean updateBatchById(Collection entityList); // 根据ID 批量更新 boolean updateBatchById(Collection entityList, int batchSize);get// 根据 ID 查询 T getById(Serializable id); // 根据 Wrapper,查询一条记录。结果集,如果是多个会抛出异常,随机取一条加上限制条件 wrapper.last("LIMIT 1") T getOne(Wrapper queryWrapper); // 根据 Wrapper,查询一条记录 T getOne(Wrapper queryWrapper, boolean throwEx); // 根据 Wrapper,查询一条记录 Map getMap(Wrapper queryWrapper); // 根据 Wrapper,查询一条记录 V getObj(Wrapper queryWrapper, Function<? super Object, V> mapper);list// 查询所有 List list(); // 查询列表 List list(Wrapper queryWrapper); // 查询(根据ID 批量查询) Collection listByIds(Collection<? extends Serializable> idList); // 查询(根据 columnMap 条件) Collection listByMap(Map columnMap); // 查询所有列表 List