转载

MybatisPlus3.1.1-BaseMapper<T>功能介绍

MybatisPlus3.1.1-BaseMapper&lt;T&gt;功能介绍

MybatisPlus引言

MybatisPlus(简称MP)是一个Mybatis的增强工具,在 Mybatis 的基础上只做增强不做改变,为简化开发、提高效率而生。

只需要将一个Mapper继承BaseMapper即可完成单表的所有CRUD操作,形式之多样,功能之丰富,令人之叹服!

本次测试环境

  • MybatisPlus-3.1.1
  • mysql-5.27
  • SpringBoot-2.1.9
  • lombok

基本用法

不想看测试用例的,可以直接看总结部分,对测试代码感兴趣的可以访问https://github.com/Cliff-Ford/mybatisplus-demo.git

//City实体类
@Data
@Builder
public class City {
    @TableId(type = IdType.AUTO)
    private Integer id;

    private String name;

    @TableField("CountryCode")
    private String countryCode;

    private String district;

    private Integer population;
}
复制代码
//CityMapper
@Repository
@Mapper
public interface CityMapper extends BaseMapper<City> {
}
复制代码
//分页拦截器
@Configuration
public class MybatisPlusConfig {
    @Bean
    public PaginationInterceptor paginationInterceptor() {
        return new PaginationInterceptor();
    }
}
复制代码

10种select方法

  1. T selectById(Serializable id);

    简介:根据id查找,返回一个实体类对象

    注意:@TableId注解是否已打上

    用例:

    @Test
    public void testSelectById() {
        log.info(String.valueOf(cityMapper.selectById(1)));
    }
    复制代码
  2. List selectBatchIds(@Param(Constants.COLLECTION) Collection<? extends Serializable> idList);

    简介:根据id数组进行查找,返回一个List对象

    注意:id数组不可为null,数组长度必须大于0

    用例:

    @Test
    public void testSelectBatchIds() {
        log.info(String.valueOf(cityMapper.selectBatchIds(Arrays.asList(1, 2, 3, 4, 5))));
        //log.info(String.valueOf(cityMapper.selectBatchIds(null)));
        //log.info(String.valueOf(cityMapper.selectBatchIds(new ArrayList<>())));
    }
    复制代码
  3. List selectByMap(@Param(Constants.COLUMN_MAP) Map<String, Object> columnMap);

    简介:根据map对象查找,条件是等于,返回一个List对象

    注意:map为null或者map对象内没有元素时进行全表查询

    用例:

    @Test
    public void testSelectByMap() {
        HashMap<String, Object> cityQueryMap = new HashMap<>();
        cityQueryMap.put("district", "Rio Grande do Sul");
        log.info(String.valueOf(cityMapper.selectByMap(cityQueryMap)));
        //log.info(String.valueOf(cityMapper.selectByMap(null)));
        //log.info(String.valueOf(cityMapper.selectByMap(new HashMap<>())));
    }
    复制代码
  4. T selectOne(@Param(Constants.WRAPPER) Wrapper queryWrapper);

    简介:根据queryWrapper查找,返回一个实体类对象或者null

    注意:selectOne的查询结果数不是小于等于一条时会报错,如果根据id查询,通常用selectById,这里可能是联合索引/逻辑主键的一个使用

    用例:

    @Test
    public void testSelectOne() {
        QueryWrapper<City> cityQueryWrapper = new QueryWrapper<City>()
                .eq("id", 300)
                .eq("countryCode", "BRA");
        log.info(String.valueOf(cityMapper.selectOne(cityQueryWrapper)));
    }
    复制代码
  5. Integer selectCount(@Param(Constants.WRAPPER) Wrapper queryWrapper);

    简介:根据queryWrapper统计条数

    注意:queryWrapper为null时统计全表记录数

    用例:

    @Test
    public void testSelectCountWithoutWrapper() {
        log.info(String.valueOf(cityMapper.selectCount(null)));
    }
    复制代码
  6. List selectList(@Param(Constants.WRAPPER) Wrapper queryWrapper);

    简介:根据queryWrapper查找,返回一个List对象

    注意:queryWrapper为null时全表查询

    用例:

    @Test
    public void testSelectListWithoutWrapper() {
        log.info(String.valueOf(cityMapper.selectList(null)));
    }
    
    @Test
    public void testSelectListWithWrapper() {
        QueryWrapper<City> cityQueryWrapper = new QueryWrapper<City>().le("id", 300);
        log.info(String.valueOf(cityMapper.selectList(cityQueryWrapper)));
    }
    复制代码
  7. List<Map<String, Object>> selectMaps(@Param(Constants.WRAPPER) Wrapper queryWrapper);

    简介:根据queryWrapper查找,返回一个List对象,List内的元素是一个map对象

    注意:map对象内的key是对应表的字段名

    用例:

    @Test
    public void testSelectMaps() {
        List<Map<String, Object>> maps = cityMapper.selectMaps(new QueryWrapper<City>().eq("name", "haha"));
        log.info(String.valueOf(maps));
        //每一个key都是表中的字段名
        log.info(String.valueOf(maps.get(0).keySet()));
    }
    复制代码
  8. List selectObjs(@Param(Constants.WRAPPER) Wrapper queryWrapper);

    简介:根据queryWrapper查找,返回一组id值

    用例:

    @Test
    public void testSelectObjects() {
        List<Object> cities = cityMapper.selectObjs(new QueryWrapper<City>().eq("name", "haha"));
        //只返回id,有点奇怪
        log.info(String.valueOf(cities));
        if(cities.size() > 0){
            log.info(String.valueOf(cities.get(0)));
        }
    }
    复制代码
  9. IPage selectPage(IPage page, @Param(Constants.WRAPPER) Wrapper queryWrapper);

    简介:根据queryWrapper分页查找,返回一个IPage对象

    注意:是否配置了分页拦截器

    用例:

    @Test
    public void testSelectPage() {
        Page<City> cityPage = new Page<>(2,4);
        QueryWrapper<City> cityQueryWrapper = new QueryWrapper<City>().eq("name", "haha");
        IPage<City> cityIPage = cityMapper.selectPage(cityPage, cityQueryWrapper);
        if (cityIPage != null){
            log.info(String.valueOf(cityIPage.getPages()));
            log.info(String.valueOf(cityIPage.getTotal()));
            log.info(String.valueOf(cityIPage.getCurrent()));
            log.info(String.valueOf(cityIPage.getRecords()));
            log.info(String.valueOf(cityIPage.getSize()));
        }
    }
    复制代码
  10. IPage<Map<String, Object>> selectMapsPage(IPage page, @Param(Constants.WRAPPER) Wrapper queryWrapper);

    简介:根据Wrapper查找,返回一个IPage对象,records内元素是一个个map对象

    注意:map对象的key是对应表的字段名

    用例:

    @Test
    public void testSelectMapsPage() {
        Page<City> cityPage = new Page<>(2,4);
        QueryWrapper<City> cityQueryWrapper = new QueryWrapper<City>().eq("name", "haha");
        IPage<Map<String, Object>> mapsPage = cityMapper.selectMapsPage(cityPage, cityQueryWrapper);
        if(mapsPage != null){
            log.info(String.format("当前页:%s", mapsPage.getCurrent()));
            log.info(String.format("当前页条数:%d", mapsPage.getRecords().size()));
            log.info(String.format("当前页记录:%s", mapsPage.getRecords()));
            log.info(String.format("总页数:%s", mapsPage.getPages()));
            log.info(String.format("总条数:%s", mapsPage.getTotal()));
            log.info(String.format("每页最大条数:%s", mapsPage.getSize()));
        }
    }
    复制代码
  11. 1种insert方法

    1. int insert(T entity);

      简介:将构造的实体对象插入数据库

      注意:如果数据库有自增id,注意@TableId是否正确选择了IdType,@Transactional和@Rollback结合一起使用才不会对数据库产生影响

      用例:

      @Test
      @Transactional
      @Rollback
      public void testInsert() {
          Integer beforeInsert = cityMapper.selectCount(null);
          City city = City.builder().name("HaHa").countryCode("ARM").population(4800).build();
          cityMapper.insert(city);
          Integer afterInsert = cityMapper.selectCount(null);
          log.info("id --> " + city.getId());
          log.info("beforeInsert --> " + beforeInsert);
          log.info("afterInsert --> " + afterInsert);
          Assert.assertEquals(1, afterInsert-beforeInsert);
      }
      复制代码

    2种update方法

    1. int updateById(@Param(Constants.ENTITY) T entity);

      简介:根据实体对象的id查找,再对查找到的记录进行修改,返回受影响的条数

      用例:

      @Test
      @Transactional
      @Rollback
      public void testUpdateById1() {
          City beforeUpdate = cityMapper.selectById(1);
          log.info(String.valueOf(beforeUpdate));
          City updateCity = City.builder().id(1).name("haha").build();
          //updateCity对象中未设置值的字段保留原记录的值,而不是将原记录设置为空值,对比testUpdateById2会更好理解
          int num = cityMapper.updateById(updateCity);
          log.info(String.format("跟新了%d条", num));
          City afterUpdate = cityMapper.selectById(1);
          log.info(String.valueOf(afterUpdate));
      }
      
      @Test
      @Transactional
      @Rollback
      public void testUpdateById2() {
          City beforeUpdate = cityMapper.selectById(1);
          log.info(String.valueOf(beforeUpdate));
          beforeUpdate.setName("haha");
          //beforeUpdate对象对目标字段的值做出了修改,对比testUpdateById1阅读
          int num = cityMapper.updateById(beforeUpdate);
          log.info(String.format("跟新了%d条", num));
          City afterUpdate = cityMapper.selectById(1);
          log.info(String.valueOf(afterUpdate));
      }
      复制代码
    2. int update(@Param(Constants.ENTITY) T entity, @Param(Constants.WRAPPER) Wrapper updateWrapper);简介:根据updateWrapper查找,再根据entity对象设值,返回受影响的条数

      注意:updateWrapper为空时全表更新,用queryWrapper代替updateWrapper也行

      用例:

      @Test
      @Transactional
      @Rollback
      public void testUpdateWithoutWrapper() {
          City cityForUpdate = City.builder().name("a").build();
          //严禁这种超危动作,测试用
          int num = cityMapper.update(cityForUpdate, null);
          log.info(String.format("更新了%d条", num));
      }
      
      
      @Test
      @Transactional
      @Rollback
      public void testUpdateWithoutQueryWrapper() {
          City cityForUpdate = City.builder().name("a").build();
          QueryWrapper<City> cityQueryWrapper = new QueryWrapper<City>().eq("name", "haha");
          int num = cityMapper.update(cityForUpdate, cityQueryWrapper);
          log.info(String.format("更新了%d条", num));
          log.info(String.valueOf(cityMapper.selectList(new QueryWrapper<City>().eq("name","a"))));
      }
      
      @Test
      @Transactional
      @Rollback
      public void testUpdateWithoutUpdateWrapper() {
          City cityForUpdate = City.builder().name("a").build();
          UpdateWrapper<City> cityUpdateWrapper = new UpdateWrapper<City>().eq("name", "haha");
          int num = cityMapper.update(cityForUpdate, cityUpdateWrapper);
          log.info(String.format("更新了%d条", num));
          log.info(String.valueOf(cityMapper.selectList(new QueryWrapper<City>().eq("name","a"))));
      }
      复制代码

    4种delete方法

    1. int deleteById(Serializable id);

      简介:根据id删除,返回受影响的条数

      用例:

      @Test
      @Transactional
      @Rollback
      public void testDeleteById() {
          City cityBeforeDelete = cityMapper.selectById(3);
          //deleteById方法返回受影响的条数
          int num = cityMapper.deleteById(cityBeforeDelete.getId());
          log.info(String.format("删除了%s条", num));
          City cityAfterDelete = cityMapper.selectById(cityBeforeDelete.getId());
          log.info(String.valueOf(cityAfterDelete));
      }
      复制代码
    2. int deleteByMap(@Param(Constants.COLUMN_MAP) Map<String, Object> columnMap);

      简介:根据map对象删除,返回受影响的条数

      注意:key=columnName,value=columnValue

      用例:

      @Test
      @Transactional
      @Rollback
      public void testDeleteByMap() {
          HashMap<String, Object> deleteMap = new HashMap<>();
          deleteMap.put("name", "haha");
          int num = cityMapper.deleteByMap(deleteMap);
          log.info(String.format("删除了%d条", num));
      }
      复制代码
    3. int delete(@Param(Constants.WRAPPER) Wrapper wrapper);

      简介:根据wrapper删除,返回受影响的条数

      注意:wrapper为null时全表删除

      用例:

      @Test
      @Transactional
      @Rollback
      public void testDeleteWithoutWrapper() {
          int num = cityMapper.delete(null);
          log.info(String.format("删除了%d条", num));
      }
      
      @Test
      @Transactional
      @Rollback
      public void testDeleteWithWrapper() {
          QueryWrapper<City> cityQueryWrapper = new QueryWrapper<City>().eq("name", "haha");
          int num = cityMapper.delete(cityQueryWrapper);
          log.info(String.format("删除了%d条", num));
      }
      复制代码
    4. int deleteBatchIds(@Param(Constants.COLLECTION) Collection<? extends Serializable> idList);

      简介:根据id数组删除,返回受影响的条数

      注意:数组不能为null,且size()大于0

      用例:

      @Test
      @Transactional
      @Rollback
      public void testDeleteBatchIds() {
          int num = cityMapper.deleteBatchIds(Arrays.asList(1, 2, 3, 4, 5));
          log.info(String.format("删除了%d条", num));
      }
      复制代码

    总结

    操作 入参 返回值
    selectById 主键id 实体类T
    selectBatchIds 主键id数组 实体类数组List<T>
    selectByMap Map对象 实体类数组List<T>
    selectOne queryWrapper 实体类T
    selectCount queryWrapper queryWrapper条件下的条目数
    selectList queryWrapper 实体类数组List<T>
    selectMaps queryWrapper Map对象数组
    selectObjs queryWrapper id主键数组
    selectPage queryWrapper IPage<T>对象,包含了总记录条数,分页等信息
    insert 实体对象T 受影响条数
    updateById 实体对象T 受影响条数
    update 实体对象T作为set部分,queryWrapper对象作为where查询部分 受影响条数
    deleteById 主键id 受影响条数
    deleteByMap Map对象 受影响条数
    delete queryWrapper对象作为where查询部分 受影响条数
    deleteBatchIds 主键id数组 受影响条数
原文  https://juejin.im/post/5d9853ca5188253e2a3da25f
正文到此结束
Loading...