您当前的位置:首页 > 电脑百科 > 程序开发 > 框架

MybatisPlus生成器ServiceImpl类详解

时间:2022-08-03 11:54:40  来源:  作者:是啊超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就已经注入了进来,不需要重新注入。



Tags:MybatisPlus   点击:()  评论:()
声明:本站部分内容及图片来自互联网,转载是出于传递更多信息之目的,内容观点仅代表作者本人,如有任何标注错误或版权侵犯请与我们联系(Email:2595517585@qq.com),我们将及时更正、删除,谢谢。
▌相关推荐
ServiceImpl类是我们进行SQL操作中非常重要的一个类,通过MybatisPlus生成的各个实体类的XXXImpl都会继承ServiceImpl类那里继承全部的方法,那么ServiceImpl类中有哪些方法呢?如...【详细内容】
2022-08-03  Tags: MybatisPlus  点击:(413)  评论:(0)  加入收藏
今天介绍一个 MyBatis - Plus 官方发布的神器:mybatis-mate 为 mp 企业级模块,支持分库分表,数据审计、数据敏感词过滤(AC算法),字段加密,字典回写(数据绑定),数据权限,表结构自动生成...【详细内容】
2022-06-17  Tags: MybatisPlus  点击:(101)  评论:(0)  加入收藏
1. Mybatis 存在的痛点我们知道 MyBatis 是一个基于 java 的持久层框架,它内部封装了 jdbc,极大提高了我们的开发效率。但是使用 Mybatis 开发也有很多痛点: 每个 Dao 接口都需...【详细内容】
2022-06-14  Tags: MybatisPlus  点击:(110)  评论:(0)  加入收藏
MybatisPlus是国产的第三方插件, 它封装了许多常用的CURDapi,免去了我们写mapper.xml的重复劳动,这里介绍了基本的整合SpringBoot和基础用法。2|0引入依赖在项目中pom文件引入m...【详细内容】
2022-05-05  Tags: MybatisPlus  点击:(90)  评论:(0)  加入收藏
SpringBoot 集成 MybatisPlus 系列SpringBoot 版本:2.6.4 MybatisPlus 版本:3.5.1 SpringBoot整合MybatisPlus SpringBoot整合MybatisPlus数据自动填充 SpringBoot整合Mybatis...【详细内容】
2022-03-18  Tags: MybatisPlus  点击:(271)  评论:(0)  加入收藏
一、前言1.1、关于枚举类① 枚举是JDK1.5中的新功能,我们可以使用枚举很好的去描述一些业务场景:一年有四季、人类有男女...② 同样我们在业务层面会有很多,比如状态属性、分...【详细内容】
2022-01-20  Tags: MybatisPlus  点击:(344)  评论:(0)  加入收藏
(一)前言最早写JDBC的时候,要手动配连接信息,要一条条手写sql语句。后来Mybatis出现了,不需要再手动配置连接信息,sql语句也和代码隔离开来,但是还免不了写Sql。接着出现了MybatisP...【详细内容】
2021-09-17  Tags: MybatisPlus  点击:(224)  评论:(0)  加入收藏
▌简易百科推荐
说明目前重点放在别的东西上,所以这个插件不再更新,只能用于pc端,移动端自己可以fork进行优化。Installyarn add vue-draggingHow to use普通html<script src="./vue.js"></scr...【详细内容】
2022-10-21  桥湾村的希望  今日头条  Tags:Vue   点击:(7)  评论:(0)  加入收藏
大厂技术 坚持周更 精选好文本文为来自 教育-智能学习-前端团队成员的文章,已授权 ELab 发布。智能学习前端团队自创立以来,团队专注于打破大众对教育的刻板印象,突破固有的教...【详细内容】
2022-10-14  ELab  今日头条  Tags:Tauri   点击:(11)  评论:(0)  加入收藏
根据官方的文档说明:Spring Data JPA - Reference Documentation 可以在查询的参数后面添加 True 或 False 来进行查询。例如,如果需要对下面的参数进行查询:True findByAct...【详细内容】
2022-10-11  松鼠工厂  今日头条  Tags:Spring   点击:(12)  评论:(0)  加入收藏
使用过Spring Data操作ES的小伙伴应该有所了解,它只能实现一些非常基本的数据管理工作,一旦遇到稍微复杂点的查询,基本都要依赖ES官方提供的RestHighLevelClient,Spring Data只...【详细内容】
2022-10-11  Java编程指南    Tags:MyBatis   点击:(22)  评论:(0)  加入收藏
概念IOC:控制反转。从前需要在程序中创建对象实例;现在则通过一个外部的容器统一动态创建spring IOC 容器中的实例如何动态加载Condition:只有在特定条件满足时才加载举例 @Con...【详细内容】
2022-10-10  小技术酱  今日头条  Tags:Springboot   点击:(96)  评论:(0)  加入收藏
简介在项目中,存在传递超大 json 数据的场景。直接传输超大 json 数据的话,有以下两个弊端 占用网络带宽,而有些云产品就是按照带宽来计费的,间接浪费了钱 传输数据大导致网络...【详细内容】
2022-10-10    网易号  Tags:Springboot   点击:(22)  评论:(0)  加入收藏
简介Tokio 是 Rust 世界里最著名的异步执行框架,该框架包罗了几乎所有异步执行的接口,包括但不限于文件、网络和文件系统管理。在这些方便使用的高层接口之下则是一些“基石...【详细内容】
2022-10-07  达坦科技DateLord  今日头条  Tags:Tokio   点击:(19)  评论:(0)  加入收藏
/ 前言 /我收回标题上的话,从0手撸一个框架一点也不轻松,需要考虑的地方比较多,一些实现和细节值得商榷,是一个比较大的挑战,有不足的地方欢迎大佬们提供意见/ 依赖任务加载 /平...【详细内容】
2022-10-07  Meta多元宇宙  今日头条  Tags:框架   点击:(20)  评论:(0)  加入收藏
一、全局配置自定义1、代码配置 方式一:让父子上下文ComponentScan重叠(强烈不建议使用) @Configurationpublic class StockFeignConfiguration { /** * 日志级别...【详细内容】
2022-10-07  Java架构师知识  今日头条  Tags:Spring Cloud   点击:(16)  评论:(0)  加入收藏
摘要:本文介绍了Sermant Agent的接入原理和如何使用Sermant Agent无修改接入CSE。 本文分享自华为云社区《【技术干货】Spring Cloud应用零代码修改接入华为云微服务引擎CSE-...【详细内容】
2022-10-06  华为云开发者联盟  今日头条  Tags:Spring Cloud   点击:(23)  评论:(0)  加入收藏
站内最新
站内热门
站内头条