Mybatis-plus学习(二)——MybatiPlus的BaseMapper和IService详解以及自定义实现

发布于 2020-12-05  5089 次阅读


Mybatis-plus学习(二)——MybatiPlus的BaseMapper和IService详解以及自定义实现

2.使用BaseMapper以及了解其原理

2.1查看BaseMapper的源码

AccountDao.java接口继承于mybatis-plus提供的BaseMapper.java接口,而BaseMapper.java接口继承于Mapper.java接口。我们首先看Mapper.java接口里面的方法:

**
 * 顶级Mapper
 *
 * @author nieqiurong 2019/4/13.
 */
public interface Mapper<T> {

}

该接口里面没有任何方法,只是定义了一个接口类。

然后接着看BaseMapper.java接口:

/**
 * Mapper 继承该接口后,无需编写 mapper.xml 文件,即可获得CRUD功能
 * <p>这个 Mapper 支持 id 泛型</p>
 *
 * @author hubin
 * @since 2016-01-23
 */
public interface BaseMapper<T> extends Mapper<T> {

    /**
     * 插入一条记录
     *
     * @param entity 实体对象
     */
    int insert(T entity);

    /**
     * 根据 ID 删除
     *
     * @param id 主键ID
     */
    int deleteById(Serializable id);

    /**
     * 根据 columnMap 条件,删除记录
     *
     * @param columnMap 表字段 map 对象
     */
    int deleteByMap(@Param(Constants.COLUMN_MAP) Map<String, Object> columnMap);

    /**
     * 根据 entity 条件,删除记录
     *
     * @param queryWrapper 实体对象封装操作类(可以为 null,里面的 entity 用于生成 where 语句)
     */
    int delete(@Param(Constants.WRAPPER) Wrapper<T> queryWrapper);

    /**
     * 删除(根据ID 批量删除)
     *
     * @param idList 主键ID列表(不能为 null 以及 empty)
     */
    int deleteBatchIds(@Param(Constants.COLLECTION) Collection<? extends Serializable> idList);

    /**
     * 根据 ID 修改
     *
     * @param entity 实体对象
     */
    int updateById(@Param(Constants.ENTITY) T entity);

    /**
     * 根据 whereEntity 条件,更新记录
     *
     * @param entity        实体对象 (set 条件值,可以为 null)
     * @param updateWrapper 实体对象封装操作类(可以为 null,里面的 entity 用于生成 where 语句)
     */
    int update(@Param(Constants.ENTITY) T entity, @Param(Constants.WRAPPER) Wrapper<T> updateWrapper);

    /**
     * 根据 ID 查询
     *
     * @param id 主键ID
     */
    T selectById(Serializable id);

    /**
     * 查询(根据ID 批量查询)
     *
     * @param idList 主键ID列表(不能为 null 以及 empty)
     */
    List<T> selectBatchIds(@Param(Constants.COLLECTION) Collection<? extends Serializable> idList);

    /**
     * 查询(根据 columnMap 条件)
     *
     * @param columnMap 表字段 map 对象
     */
    List<T> selectByMap(@Param(Constants.COLUMN_MAP) Map<String, Object> columnMap);

    /**
     * 根据 entity 条件,查询一条记录
     *
     * @param queryWrapper 实体对象封装操作类(可以为 null)
     */
    T selectOne(@Param(Constants.WRAPPER) Wrapper<T> queryWrapper);

    /**
     * 根据 Wrapper 条件,查询总记录数
     *
     * @param queryWrapper 实体对象封装操作类(可以为 null)
     */
    Integer selectCount(@Param(Constants.WRAPPER) Wrapper<T> queryWrapper);

    /**
     * 根据 entity 条件,查询全部记录
     *
     * @param queryWrapper 实体对象封装操作类(可以为 null)
     */
    List<T> selectList(@Param(Constants.WRAPPER) Wrapper<T> queryWrapper);

    /**
     * 根据 Wrapper 条件,查询全部记录
     *
     * @param queryWrapper 实体对象封装操作类(可以为 null)
     */
    List<Map<String, Object>> selectMaps(@Param(Constants.WRAPPER) Wrapper<T> queryWrapper);

    /**
     * 根据 Wrapper 条件,查询全部记录
     * <p>注意: 只返回第一个字段的值</p>
     *
     * @param queryWrapper 实体对象封装操作类(可以为 null)
     */
    List<Object> selectObjs(@Param(Constants.WRAPPER) Wrapper<T> queryWrapper);

    /**
     * 根据 entity 条件,查询全部记录(并翻页)
     *
     * @param page         分页查询条件(可以为 RowBounds.DEFAULT)
     * @param queryWrapper 实体对象封装操作类(可以为 null)
     */
    <E extends IPage<T>> E selectPage(E page, @Param(Constants.WRAPPER) Wrapper<T> queryWrapper);

    /**
     * 根据 Wrapper 条件,查询全部记录(并翻页)
     *
     * @param page         分页查询条件
     * @param queryWrapper 实体对象封装操作类
     */
    <E extends IPage<Map<String, Object>>> E selectMapsPage(E page, @Param(Constants.WRAPPER) Wrapper<T> queryWrapper);
}

通过阅读源码,我们发现该接口定义了很多用于操作数据库实现增删查改(CRUD)功能的函数。具体的函数以及它的功能源码中已经有说明了。

2.1测试Mapper的增删查改功能

package com.moyisuiying.booksystem;

import com.moyisuiying.booksystem.dao.AccountDao;
import com.moyisuiying.booksystem.entity.Account;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;

import java.util.Arrays;
import java.util.List;

@SpringBootTest
class BooksystemApplicationTests {
    @Autowired
    AccountDao accountDao;
    @Test
    public  void testFindAll(){
        List<Account> accountList = accountDao.selectList(null);
        accountList.forEach(System.out::println);
    }
    @Test
   public void testFindById(){
       Account account = accountDao.selectById(19);
       System.out.println(account);
   }
   @Test
    public void testInsert(){
        Account account = new Account(28,"张三","bb");
       int fla = accountDao.insert(account);
       System.out.println(fla);

   }
   @Test
   public void testDeleteById(){
       int deleted = accountDao.deleteById(21);
       System.out.println(deleted);
   }
   @Test
   public void testDeleteByIds(){
       int deleteBatchIds = accountDao.deleteBatchIds(Arrays.asList(22, 23));
       System.out.println(deleteBatchIds);
   }
   @Test
    public void testUpdate(){
        Account account = new Account();
        account.setId(27);
        account.setName("李四");
        account.setPassword("232335");
       int update = accountDao.updateById(account);
       System.out.println(update);
   }
}

3 .使用通用的IService实现crud功能以及了解它的原理

3.1首先看mybatisplus提供的通用IService.java这个接口类提供的方法

3.1.1Service CRUD 接口

①通用 Service CRUD 封装IService接口,进一步封装 CRUD 采用 get 查询单行 remove 删除 list 查询集合 page 分页 前缀命名方式区分 Mapper 层避免混淆,

②泛型 T 为任意实体对象

③建议如果存在自定义通用 Service 方法的可能,请创建自己的 IBaseService 继承 Mybatis-Plus 提供的基类

④对象 Wrapper条件构造器

⑤IService 的默认实现类为ServiceImpl.java

在这里插入图片描述

从这个实现类中我们可以看到,ServiceImpl.java使用了BaseMapper或者BaseMapper的子类用于实现增删查改等功能,实际上也就是在BaseMapper功能的基础上封装了一些方法。ServiceImpl功能的实现还是要依赖于BaseMapper。

3.1.2Save

// 插入一条记录(选择字段,策略插入)
boolean save(T entity);
// 插入(批量)
boolean saveBatch(Collection<T> entityList);
// 插入(批量)
boolean saveBatch(Collection<T> entityList, int batchSize);
参数说明
类型参数名描述
Tentity实体对象
CollectionentityList实体对象集合
intbatchSize插入批次数量

3.1.4SaveOrUpdate

// TableId 注解存在更新记录,否插入一条记录
boolean saveOrUpdate(T entity);
// 根据updateWrapper尝试更新,否继续执行saveOrUpdate(T)方法
boolean saveOrUpdate(T entity, Wrapper<T> updateWrapper);
// 批量修改插入
boolean saveOrUpdateBatch(Collection<T> entityList);
// 批量修改插入
boolean saveOrUpdateBatch(Collection<T> entityList, int batchSize);
参数说明
类型参数名描述
Tentity实体对象
WrapperupdateWrapper实体对象封装操作类 UpdateWrapper
CollectionentityList实体对象集合
intbatchSize插入批次数量

3.1.5Remove

// 根据 entity 条件,删除记录
boolean remove(Wrapper<T> queryWrapper);
// 根据 ID 删除
boolean removeById(Serializable id);
// 根据 columnMap 条件,删除记录
boolean removeByMap(Map<String, Object> columnMap);
// 删除(根据ID 批量删除)
boolean removeByIds(Collection<? extends Serializable> idList);
参数说明
类型参数名描述
WrapperqueryWrapper实体包装类 QueryWrapper
Serializableid主键ID
MapcolumnMap表字段 map 对象
CollectionidList主键ID列表

3.1.6Update

// 根据 UpdateWrapper 条件,更新记录 需要设置sqlset
boolean update(Wrapper<T> updateWrapper);
// 根据 whereEntity 条件,更新记录
boolean update(T entity, Wrapper<T> updateWrapper);
// 根据 ID 选择修改
boolean updateById(T entity);
// 根据ID 批量更新
boolean updateBatchById(Collection<T> entityList);
// 根据ID 批量更新
boolean updateBatchById(Collection<T> entityList, int batchSize);
参数说明
类型参数名描述
WrapperupdateWrapper实体对象封装操作类 UpdateWrapper
Tentity实体对象
CollectionentityList实体对象集合
intbatchSize更新批次数量

3.1.7Get

// 根据 ID 查询
T getById(Serializable id);
// 根据 Wrapper,查询一条记录。结果集,如果是多个会抛出异常,随机取一条加上限制条件 wrapper.last("LIMIT 1")
T getOne(Wrapper<T> queryWrapper);
// 根据 Wrapper,查询一条记录
T getOne(Wrapper<T> queryWrapper, boolean throwEx);
// 根据 Wrapper,查询一条记录
Map<String, Object> getMap(Wrapper<T> queryWrapper);
// 根据 Wrapper,查询一条记录
<V> V getObj(Wrapper<T> queryWrapper, Function<? super Object, V> mapper);
参数说明
类型参数名描述
Serializableid主键ID
WrapperqueryWrapper实体对象封装操作类 QueryWrapper
booleanthrowEx有多个 result 是否抛出异常
Tentity实体对象
Functionmapper转换函数

3.1.8List

// 查询所有
List<T> list();
// 查询列表
List<T> list(Wrapper<T> queryWrapper);
// 查询(根据ID 批量查询)
Collection<T> listByIds(Collection<? extends Serializable> idList);
// 查询(根据 columnMap 条件)
Collection<T> listByMap(Map<String, Object> columnMap);
// 查询所有列表
List<Map<String, Object>> listMaps();
// 查询列表
List<Map<String, Object>> listMaps(Wrapper<T> queryWrapper);
// 查询全部记录
List<Object> listObjs();
// 查询全部记录
<V> List<V> listObjs(Function<? super Object, V> mapper);
// 根据 Wrapper 条件,查询全部记录
List<Object> listObjs(Wrapper<T> queryWrapper);
// 根据 Wrapper 条件,查询全部记录
<V> List<V> listObjs(Wrapper<T> queryWrapper, Function<? super Object, V> mapper);
参数说明
类型参数名描述
WrapperqueryWrapper实体对象封装操作类 QueryWrapper
CollectionidList主键ID列表
MapcolumnMap表字段 map 对象
Functionmapper转换函数

3.1.9Page

// 无条件分页查询
IPage<T> page(IPage<T> page);
// 条件分页查询
IPage<T> page(IPage<T> page, Wrapper<T> queryWrapper);
// 无条件分页查询
IPage<Map<String, Object>> pageMaps(IPage<T> page);
// 条件分页查询
IPage<Map<String, Object>> pageMaps(IPage<T> page, Wrapper<T> queryWrapper);
参数说明
类型参数名描述
IPagepage翻页对象
WrapperqueryWrapper实体对象封装操作类 QueryWrapper

3.1.10Count

// 查询总记录数
int count();
// 根据 Wrapper 条件,查询总记录数
int count(Wrapper<T> queryWrapper);
参数说明
类型参数名描述
WrapperqueryWrapper实体对象封装操作类 QueryWrapper

3.1.11Chain

query

// 链式查询 普通
QueryChainWrapper<T> query();
// 链式查询 lambda 式。注意:不支持 Kotlin
LambdaQueryChainWrapper<T> lambdaQuery(); 

// 示例:
query().eq("column", value).one();
lambdaQuery().eq(Entity::getId, value).list();

update

// 链式更改 普通
UpdateChainWrapper<T> update();
// 链式更改 lambda 式。注意:不支持 Kotlin 
LambdaUpdateChainWrapper<T> lambdaUpdate();

// 示例:
update().eq("column", value).remove();
lambdaUpdate().eq(Entity::getId, value).update(entity);

3.2自定义一个继承于IService.java接口的AccountService.java接口,然后实现它

public interface AccountService extends IService<Account> {
    /**
     * @Description :自定义的方法,用于实现用户Account登录逻辑实现
     * @Date 12:14 2020/11/25 0025
     * @Param * @param name  用户名
     * @param password :密码
     * @return com.moyisuiying.booksystem.entity.Account
     **/
    public Account login(String name, String password);
}
@Service("accountService")
public class AccountServiceImpl  extends ServiceImpl<BaseMapper<Account>, Account> implements AccountService{
     @Override
    public Account login(String name, String password) {
        //实例化查询条件对象
        QueryWrapper<Account> queryWrapper = new QueryWrapper<>();
        //设置查询条件
        queryWrapper.eq("name",name).eq("password", password);
        Account loginUser = this.getOne(queryWrapper);
        return  loginUser;
    }
}

3.3开始测试

package com.moyisuiying.booksystem;

import com.moyisuiying.booksystem.entity.Account;
import com.moyisuiying.booksystem.service.AccountService;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;

import java.util.Arrays;
import java.util.List;

/**
 * Classname:AccountServiceTest
 *
 * @description:
 * @author: 陌意随影
 * @Date: 2020-11-25 11:40
 * @Version: 1.0
 **/
@SpringBootTest
public class AccountServiceTest {
    @Autowired
    AccountService accountService;
    @Test
    public void testSave(){
        Account account = new Account(1,"陌意随影","1234");
        boolean save = accountService.save(account);
        System.out.println(save);
    }
    @Test
    public void testUpdate(){
        Account newAccount = new Account();
        newAccount.setPassword("陌意随影");
        newAccount.setPassword("root");
        newAccount.setId(1);
        boolean updateById = accountService.updateById(newAccount);
        System.out.println(updateById);
    }
    @Test
    public void testRemoveById(){
        boolean b = accountService.removeById(25);
        System.out.println(b);
    }
    @Test
    public void testRemoveByIds(){
        boolean b = accountService.removeByIds(Arrays.asList(19,28));
        System.out.println(b);
    }
    @Test
    public void testGetOneById(){
        Account byId = accountService.getById(1);
        System.out.println(byId);
    }
    @Test
    public void testGetAll(){
        List<Account> accountList = accountService.getBaseMapper().selectList(null);
        accountList.forEach(System.out::println);
    }
}

由于AccountService中的方法除了自定义的方法外和IService中的方法一样,所以我们不用写基本的crud代码实现mybatisplus已经 帮我们实现了。并且在AccountService中我们还可以实现更加强大的更新和查找功能。

4.测试的源代码已上传到GitHub中:https://github.com/LJF2402901363/java_study.git

在这里插入图片描述


繁华落尽,雪花漫天飞舞。