<返回更多

MybatisPlus生成器ServiceImpl类详解

2022-08-03    是啊超ya
加入收藏

ServiceImpl类是我们进行SQL操作中非常重要的一个类,通过MyBatisPlus生成的各个实体类的XXXImpl都会继承ServiceImpl类那里继承全部的方法,那么ServiceImpl类中有哪些方法呢?如下介绍:

/** * IService 实现类( 泛型:M 是 mApper 对象,T 是实体 ) * * @author hubin * @since 2018-06-23 */@SuppressWarnings("unchecked")public class ServiceImpl<M extends BaseMapper<T>, T> implements IService<T> {    protected Log log = LogFactory.getLog(getClass());    @Autowired    protected M baseMapper;    @Override    public M getBaseMapper() {        return baseMapper;    }    protected Class<T> entityClass = currentModelClass();    @Override    public Class<T> getEntityClass() {        return entityClass;    }    protected Class<T> mapperClass = currentMapperClass();    /**     * 判断数据库操作是否成功     *     * @param result 数据库操作返回影响条数     * @return boolean     * @deprecated 3.3.1     */    @Deprecated    protected boolean retBool(Integer result) {        return SqlHelper.retBool(result);    }    protected Class<T> currentMapperClass() {        return (Class<T>) ReflectionKit.getSuperClassGenericType(getClass(), 0);    }    protected Class<T> currentModelClass() {        return (Class<T>) ReflectionKit.getSuperClassGenericType(getClass(), 1);    }    /**     * 批量操作 SqlSession     *     * @deprecated 3.3.0     */    @Deprecated    protected SqlSession sqlSessionBatch() {        return SqlHelper.sqlSessionBatch(entityClass);    }    /**     * 释放sqlSession     *     * @param sqlSession session     * @deprecated 3.3.0     */    @Deprecated    protected void closeSqlSession(SqlSession sqlSession) {        SqlSessionUtils.closeSqlSession(sqlSession, GlobalConfigUtils.currentSessionFactory(entityClass));    }    /**     * 获取 SqlStatement     *     * @param sqlMethod ignore     * @return ignore     * @see #getSqlStatement(SqlMethod)     * @deprecated 3.4.0     */    @Deprecated    protected String sqlStatement(SqlMethod sqlMethod) {        return SqlHelper.table(entityClass).getSqlStatement(sqlMethod.getMethod());    }    /**     * 批量插入     *     * @param entityList ignore     * @param batchSize  ignore     * @return ignore     */    @Transactional(rollbackFor = Exception.class)    @Override    public boolean saveBatch(Collection<T> entityList, int batchSize) {        String sqlStatement = getSqlStatement(SqlMethod.INSERT_ONE);        return executeBatch(entityList, batchSize, (sqlSession, entity) -> sqlSession.insert(sqlStatement, entity));    }    /**     * 获取mapperStatementId     *     * @param sqlMethod 方法名     * @return 命名id     * @since 3.4.0     */    protected String getSqlStatement(SqlMethod sqlMethod) {        return SqlHelper.getSqlStatement(mapperClass, sqlMethod);    }    /**     * TableId 注解存在更新记录,否插入一条记录     *     * @param entity 实体对象     * @return boolean     */    @Transactional(rollbackFor = Exception.class)    @Override    public boolean saveOrUpdate(T entity) {        if (null != entity) {            TableInfo tableInfo = TableInfoHelper.getTableInfo(this.entityClass);            Assert.notNull(tableInfo, "error: can not execute. because can not find cache of TableInfo for entity!");            String keyProperty = tableInfo.getKeyProperty();            Assert.notEmpty(keyProperty, "error: can not execute. because can not find column for id from entity!");            Object idVal = ReflectionKit.getFieldValue(entity, tableInfo.getKeyProperty());            return StringUtils.checkValNull(idVal) || Objects.isNull(getById((Serializable) idVal)) ? save(entity) : updateById(entity);        }        return false;    }    @Transactional(rollbackFor = Exception.class)    @Override    public boolean saveOrUpdateBatch(Collection<T> entityList, int batchSize) {        TableInfo tableInfo = TableInfoHelper.getTableInfo(entityClass);        Assert.notNull(tableInfo, "error: can not execute. because can not find cache of TableInfo for entity!");        String keyProperty = tableInfo.getKeyProperty();        Assert.notEmpty(keyProperty, "error: can not execute. because can not find column for id from entity!");        return SqlHelper.saveOrUpdateBatch(this.entityClass, this.mapperClass, this.log, entityList, batchSize, (sqlSession, entity) -> {            Object idVal = ReflectionKit.getFieldValue(entity, keyProperty);            return StringUtils.checkValNull(idVal)                || CollectionUtils.isEmpty(sqlSession.selectList(getSqlStatement(SqlMethod.SELECT_BY_ID), entity));        }, (sqlSession, entity) -> {            MapperMethod.ParamMap<T> param = new MapperMethod.ParamMap<>();            param.put(Constants.ENTITY, entity);            sqlSession.update(getSqlStatement(SqlMethod.UPDATE_BY_ID), param);        });    }    @Transactional(rollbackFor = Exception.class)    @Override    public boolean updateBatchById(Collection<T> entityList, int batchSize) {        String sqlStatement = getSqlStatement(SqlMethod.UPDATE_BY_ID);        return executeBatch(entityList, batchSize, (sqlSession, entity) -> {            MapperMethod.ParamMap<T> param = new MapperMethod.ParamMap<>();            param.put(Constants.ENTITY, entity);            sqlSession.update(sqlStatement, param);        });    }    @Override    public T getOne(Wrapper<T> queryWrapper, boolean throwEx) {        if (throwEx) {            return baseMapper.selectOne(queryWrapper);        }        return SqlHelper.getObject(log, baseMapper.selectList(queryWrapper));    }    @Override    public Map<String, Object> getMap(Wrapper<T> queryWrapper) {        return SqlHelper.getObject(log, baseMapper.selectMaps(queryWrapper));    }    @Override    public <V> V getObj(Wrapper<T> queryWrapper, Function<? super Object, V> mapper) {        return SqlHelper.getObject(log, listObjs(queryWrapper, mapper));    }    /**     * 执行批量操作     *     * @param consumer consumer     * @since 3.3.0     * @deprecated 3.3.1 后面我打算移除掉 {@link #executeBatch(Collection, int, BiConsumer)} }.     */    @Deprecated    protected boolean executeBatch(Consumer<SqlSession> consumer) {        return SqlHelper.executeBatch(this.entityClass, this.log, consumer);    }    /**     * 执行批量操作     *     * @param list      数据集合     * @param batchSize 批量大小     * @param consumer  执行方法     * @param <E>       泛型     * @return 操作结果     * @since 3.3.1     */    protected <E> boolean executeBatch(Collection<E> list, int batchSize, BiConsumer<SqlSession, E> consumer) {        return SqlHelper.executeBatch(this.entityClass, this.log, list, batchSize, consumer);    }    /**     * 执行批量操作(默认批次提交数量{@link IService#DEFAULT_BATCH_SIZE})     *     * @param list     数据集合     * @param consumer 执行方法     * @param <E>      泛型     * @return 操作结果     * @since 3.3.1     */    protected <E> boolean executeBatch(Collection<E> list, BiConsumer<SqlSession, E> consumer) {        return executeBatch(list, DEFAULT_BATCH_SIZE, consumer);    }}

ServiceImpl类各方法(未过期)的作用

1.getBaseMapper()
2.getEntityClass()
3.saveBatch()
4.saveOrUpdate()
5.saveOrUpdateBatch()
6.updateBatchById()
7.getOne()
8.getMap()
9.getObj()

ServiceImpl类各属性的作用

1.log:打印日志
2.baseMapper:实现了许多的SQL操作
3.entityClass:实体类
4.mapperClass:映射类

BaseMapper类中各方法

ServiceImpl类中有这个类的成员变量,因此通过ServiceImpl这个类便能够操作如下方法:

1.int insert(T entity);:插入记录
2.int deleteById(Serializable id);:通过id删除指定记录
3.int deleteByMap(Map<String, Object> columnMap):通过Map集合添加删除指定记录
4.int delete(@Param(Constants.WRAPPER) Wrapper queryWrapper):通过添加构造器删除指定记录
5.int deleteBatchIds(Collection<? extends Serializable> idList):通过List集合批量删除记录


6.int updateById(T entity):根据id修改指定记录
7.int update(T entity, Wrapper updateWrapper):根据条件构造器
8.T selectById(Serializable id):根据id查询指定记录
9.List selectBatchIds(Collection<? extends Serializable> idList):根据List集合批量查询记录
10.List selectByMap(Map<String, Object> columnMap):根据Map集合查询记录


11.T selectOne(Wrapper queryWrapper):根据条件构造器查询一条记录
12.Integer selectCount(Wrapper queryWrapper):根据条件构造器查询记录总数
13.List selectList(Wrapper queryWrapper):根据条件构造器查询全部记录
14.List<Map<String, Object>> selectMaps(Wrapper queryWrapper):根据条件构造器查询全部记录
15.ist selectObjs(Wrapper queryWrapper):根据条件构造器查询全部记录
16.<E extends IPage> E selectPage(E page, Wrapper queryWrapper):根据条件构造器查询全部记录(并翻页)
17.<E extends IPage<Map<String, Object>>> E selectMapsPage(E page, Wrapper queryWrapper):根据条件构造器查询全部记录(并翻页)

Wrapper类各方法

1.getEntity():实体对象(子类实现)
2.getSqlSelectgetSqlSet():
3.getSqlComment():
4.getSqlFirst():
5.getExpression():获取 MergeSegments
6.getCustomSqlSegment():获取自定义SQL 简化自定义XML复杂情况
7.isEmptyOfWhere():查询条件为空(包含entity)
8.nonEmptyOfWhere():查询条件不为空(包含entity)
9.isEmptyOfNormal():查询条件为空(不包含entity)
10.nonEmptyOfNormal():查询条件为空(不包含entity)
11.nonEmptyOfEntity():深层实体判断属性
12.fieldStrategyMatch():根据实体FieldStrategy属性来决定判断逻辑
13.isEmptyOfEntity():深层实体判断属性
14.getTargetSql():获取格式化后的执行sql
15.clear():条件清空

实例说明

public class ServiceImpl<M extends BaseMapper<T>, T> implements IService<T> {}public class CategoryServiceImpl extends ServiceImpl<CategoryDao, CategoryEntity> implements CategoryService {}

在ServiceImpl中已经注入了Mapper对象: protected M baseMapper;因此XXXServiceImpl只要继承了这个原生的ServiceImpl,这个M实体Dao就已经注入了进来,不需要重新注入。

声明:本站部分内容来自互联网,如有版权侵犯或其他问题请与我们联系,我们将立即删除或处理。
▍相关推荐
更多资讯 >>>